package com.xbongbong.paas.service.impl;

import com.alibaba.fastjson.JSON;
import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.paas.constant.MessageConstant;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.PaasAppEntity;
import com.xbongbong.paas.domain.entity.PaasFormEntity;
import com.xbongbong.paas.domain.entity.PaasFormExplainEntity;
import com.xbongbong.paas.domain.entity.PaasMenuEntity;
import com.xbongbong.paas.domain.entity.ext.OptionalRangeEntity;
import com.xbongbong.paas.domain.entity.ext.PaasFormEntityExt;
import com.xbongbong.paas.enums.DefaultPaasModulePermissionEnum;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.EnableEnum;
import com.xbongbong.paas.enums.ModuleTypeEnum;
import com.xbongbong.paas.enums.OptionalRangeEnum;
import com.xbongbong.paas.field.LimitChooseRangePoJo;
import com.xbongbong.paas.help.CloudCodeHelp;
import com.xbongbong.paas.help.CommonHelp;
import com.xbongbong.sys.help.PackageHelp;
import com.xbongbong.paas.help.permission.PermissionHelp;
import com.xbongbong.paas.log.MongoLogHelp;
import com.xbongbong.paas.log.constant.LogMemoConstant;
import com.xbongbong.pro.message.feign.AIFeignClient;
import com.xbongbong.paas.model.FineClueCompanyModel;
import com.xbongbong.paas.model.PaasAppModel;
import com.xbongbong.paas.model.PaasFormExplainModel;
import com.xbongbong.paas.model.PaasFormModel;
import com.xbongbong.paas.model.PaasMenuModel;
import com.xbongbong.paas.model.SearchCustomerCompanyModel;
import com.xbongbong.paas.pojo.AppPermissionWithNamePojo;
import com.xbongbong.paas.pojo.BatchEditDataPermissionAppsPojo;
import com.xbongbong.paas.pojo.ModulePermissionWithNamePojo;
import com.xbongbong.paas.pojo.PermissionComplexTermPojo;
import com.xbongbong.paas.pojo.dto.BatchEditDataPermissionDTO;
import com.xbongbong.paas.pojo.dto.DetailSpecialPermissionDTO;
import com.xbongbong.paas.pojo.dto.RoleAddDTO;
import com.xbongbong.paas.pojo.dto.RoleAppDetailDTO;
import com.xbongbong.paas.pojo.dto.RoleCopyDTO;
import com.xbongbong.paas.pojo.dto.RoleDataPermissionEditDTO;
import com.xbongbong.paas.pojo.dto.RoleDeleteDTO;
import com.xbongbong.paas.pojo.dto.RoleDetailDTO;
import com.xbongbong.paas.pojo.dto.RoleEditNameDTO;
import com.xbongbong.paas.pojo.dto.RoleListDTO;
import com.xbongbong.paas.pojo.dto.RoleModuleDetailDTO;
import com.xbongbong.paas.pojo.dto.RoleSaveDTO;
import com.xbongbong.paas.pojo.dto.SaveSpecialPermissionDTO;
import com.xbongbong.paas.pojo.vo.DetailSpecialPermissionVO;
import com.xbongbong.paas.pojo.vo.IsActiveAIComboVO;
import com.xbongbong.paas.pojo.vo.RoleAddVO;
import com.xbongbong.paas.pojo.vo.RoleAppDetailVO;
import com.xbongbong.paas.pojo.vo.RoleCopyVO;
import com.xbongbong.paas.pojo.vo.RoleDataPermissionEditVO;
import com.xbongbong.paas.pojo.vo.RoleDeleteVO;
import com.xbongbong.paas.pojo.vo.RoleDetailVO;
import com.xbongbong.paas.pojo.vo.RoleEditNameVO;
import com.xbongbong.paas.pojo.vo.RoleListVO;
import com.xbongbong.paas.pojo.vo.RoleModuleDetailVO;
import com.xbongbong.paas.pojo.vo.RoleSaveVO;
import com.xbongbong.paas.redis.RedisConstant;
import com.xbongbong.paas.service.DataConnectionService;
import com.xbongbong.paas.service.RoleService;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.helper.ReflectHelper;
import com.xbongbong.paas.toolbox.pojo.AppPermissionPojo;
import com.xbongbong.paas.toolbox.pojo.ModulePermissionPojo;
import com.xbongbong.paas.toolbox.pojo.PermissionTermsPojo;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.DateUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.paas.toolbox.wrap.BaseDTO;
import com.xbongbong.paas.toolbox.wrap.BaseVO;
import com.xbongbong.paas.toolbox.wrap.RoleVO;
import com.xbongbong.paas.toolbox.wrap.XbbResponse;
import com.xbongbong.pro.constant.I18nStringConstant;
import com.xbongbong.pro.domain.entity.FineClueCompanyEntity;
import com.xbongbong.pro.domain.entity.SearchCustomerCompanyEntity;
import com.xbongbong.pro.enums.DistributorMarkEnum;
import com.xbongbong.pro.enums.ErrorCodeEnum;
import com.xbongbong.pro.enums.FineClueEnum;
import com.xbongbong.pro.enums.LimitChooseRangeTypeEnum;
import com.xbongbong.pro.enums.PackageTypeEnum;
import com.xbongbong.pro.enums.SaasMarkEnum;
import com.xbongbong.pro.enums.SoukeMealEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.enums.menu.enums.ControlCenterMenuEnum;
import com.xbongbong.pro.enums.menu.enums.SystemAppMenuEnum;
import com.xbongbong.pro.enums.permission.enums.ProPermissionAliasEnum;
import com.xbongbong.pro.packageInfo.pojo.vo.BasePackageInfoVO;
import com.xbongbong.pro.role.pojo.dto.RoleAppendOrDeleteDTO;
import com.xbongbong.pro.role.pojo.dto.RoleRecoveryDTO;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.enums.CompanyConfigEnum;
import com.xbongbong.saas.enums.OperateModuleTypeEnum;
import com.xbongbong.saas.enums.OperateTypeEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.sys.domain.entity.CompanyConfigEntity;
import com.xbongbong.sys.domain.entity.CompanyEntity;
import com.xbongbong.sys.domain.entity.CoverRoleEntity;
import com.xbongbong.sys.domain.entity.ProPermissionEntity;
import com.xbongbong.sys.domain.entity.RoleEntity;
import com.xbongbong.sys.domain.entity.UserEntity;
import com.xbongbong.sys.enums.DataPermissionEnum;
import com.xbongbong.sys.enums.RoleEnum;
import com.xbongbong.sys.model.CompanyConfigModel;
import com.xbongbong.sys.model.CompanyModel;
import com.xbongbong.sys.model.CoverRoleModel;
import com.xbongbong.sys.model.ProPermissionModel;
import com.xbongbong.sys.model.RoleModel;
import com.xbongbong.sys.model.UserModel;
import com.xbongbong.sys.pojo.DataPermissionDetailPojo;
import com.xbongbong.sys.pojo.DataPermissionsPojo;
import com.xbongbong.sys.pojo.DynamicPermissionPojo;
import com.xbongbong.sys.pojo.DynamicPermissionSubPojo;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author kaka
 * @time 2018-8-24 13:58
 */
@Service("roleService")
public class RoleServiceImpl implements RoleService {

    private static final Logger LOG = LoggerFactory.getLogger(RoleServiceImpl.class);

    @Resource
    private RoleModel roleModel;
    @Resource
    private UserModel userModel;
    @Resource
    private CoverRoleModel coverRoleModel;
    @Resource
    private PaasAppModel paasAppModel;
    @Resource
    private PaasMenuModel paasMenuModel;
    @Resource
    private ProPermissionModel proPermissionModel;
    @Resource
    private MongoLogHelp mongoLogHelp;
    @Resource
    private SearchCustomerCompanyModel searchCustomerCompanyModel;
    @Resource
    private PaasFormExplainModel paasFormExplainModel;
    @Resource
    private PaasFormModel paasFormModel;
    @Resource
    private CompanyConfigModel companyConfigModel;
    @Resource
    private CloudCodeHelp cloudCodeHelp;
    @Resource
    private PackageServiceImpl packageService;
    @Resource
    private CommonHelp commonHelp;
    @Resource
    private PackageHelp packageHelp;
    @Resource
    private FineClueCompanyModel fineClueCompanyModel;
    @Resource
    private DataConnectionService dataConnectionService;
    @Resource
    private CompanyModel companyModel;
    @Resource
    private AIFeignClient aiFeignClient;

    @Override
    public RoleListVO list(RoleListDTO roleListDTO) throws XbbException {
        Map<String, Object> param = BeanUtil.convertBean2Map(roleListDTO, true);
        RoleListVO roleListVO = new RoleListVO();
        try {
            LimitChooseRangePoJo limitChooseRange = roleListDTO.getLimitChooseRange();
            if (Objects.nonNull(limitChooseRange)) {
                LimitChooseRangeTypeEnum limitChooseRangeTypeEnum = LimitChooseRangeTypeEnum.getByType(limitChooseRange.getType());
                if (Objects.isNull(limitChooseRangeTypeEnum)) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
                }
                switch (limitChooseRangeTypeEnum) {
                    case CUSTOM:
                        List<OptionalRangeEntity> optionalRangeList = limitChooseRange.getOptionalRange();
                        if (Objects.nonNull(optionalRangeList) && !optionalRangeList.isEmpty()) {
                            List<String> roleIdIn = new ArrayList<>();
                            optionalRangeList.forEach((item)->{
                                String id = item.getId();
                                String property = item.getProperty();
                                if (OptionalRangeEnum.ROLE.getValue().equals(property)) {
                                    roleIdIn.add(id);
                                }
                            });
                            param.put("idIn", roleIdIn);
                        }
                        break;
                    case RELY:

                        break;
                    case FILTER_ADMIN:
                        List<String> roleAliasNotIn = Arrays.asList(RoleEnum.ADMIN.getRoleAlias(), RoleEnum.BOSS.getRoleAlias());
                        param.put("roleAliasNotIn", roleAliasNotIn);
                        break;
                    default:
                        throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
                }
            }
            List<RoleEntity> list = roleModel.findEntitys(param);
            List<RoleVO> roleVOs = new ArrayList<>();
            BeanUtil.copyPropertiesList(list, roleVOs, RoleVO.class);
            // 标记系统角色是否修改
            setSysRoleModifyFlag(roleVOs, roleListDTO.getCorpid());
            roleListVO.setRoleList(sortSysRole(roleVOs));
        } catch (Exception e) {
            LOG.error("RoleService 数据库查询出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        return roleListVO;
    }

    @Override
    public RoleDeleteVO delete(RoleDeleteDTO roleDeleteDTO) throws XbbException {
        RoleDeleteVO roleDeleteVO = new RoleDeleteVO();
        String corpid = roleDeleteDTO.getCorpid();
        String userId = roleDeleteDTO.getUserId();
        String userName = roleDeleteDTO.getLoginUserName();
        Integer roleId = roleDeleteDTO.getRoleId();

        RoleEntity role = roleModel.getByKey(roleId, corpid);

        if (role == null) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001.getCode(), MessageConstant.ROLE_NOT_EXIST);
        }

        if (PaasConstant.DEFAULT_DATA_CORPID.equals(role.getCorpid())) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001.getCode(), MessageConstant.NO_PERMISSION_TO_DELETE_SYS_ROLE);
        }

        // 还有员工被赋予该角色，则不能删除角色
        List<UserEntity> users = userModel.getUserWithRole(corpid, roleId);
        if (users.size() > 0) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001.getCode(), MessageConstant.NOT_ALLOW_DEL_ROLE_WITH_USER);
        }

        try {
            roleModel.deleteByKey(roleId, corpid);
        } catch (Exception e) {
            LOG.error("RoleService 数据库执行出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        // 记录日志
        String memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_DELETE_ROLE), userName, role.getRoleName());
        mongoLogHelp.buildLog(corpid, userId, userName, OperateModuleTypeEnum.ROLE, OperateTypeEnum.DELETE,
                role.getId().toString(), role.getRoleName(), memo, roleDeleteDTO.getHttpHeader());

        return roleDeleteVO;
    }

    @Override
    public RoleAddVO add(RoleAddDTO roleAddDTO) throws XbbException {
        RoleAddVO roleAddVO = new RoleAddVO();
        String corpid = roleAddDTO.getCorpid();
        String roleName = roleAddDTO.getRoleName();
        String userName = roleAddDTO.getLoginUserName();

        // 判断公司自定义角色上限
        Integer roleNum = roleModel.getCorpRoleCount(corpid);
        if (roleNum >= PaasConstant.ROLE_NUM_LIMIT) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.ROLE_NUM_EXCEED);
        }

        // 构造新角色，空权限构造方法
        RoleEntity role = new RoleEntity(corpid, roleName);

        try {
            roleModel.insert(role);
            roleAddVO.setRoleId(role.getId());
        } catch (Exception e) {
            LOG.error("RoleService 数据库执行出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        // 记录日志
        String memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_ADD_ROLE), userName, role.getRoleName());
        mongoLogHelp.buildLog(corpid, roleAddDTO.getUserId(), userName, OperateModuleTypeEnum.STAFF, OperateTypeEnum.NEW,
                role.getId().toString(), role.getRoleName(), memo, roleAddDTO.getHttpHeader());

        return roleAddVO;
    }

    @Override
    public RoleCopyVO copy(RoleCopyDTO roleCopyDTO) throws XbbException {
        RoleCopyVO roleCopyVO = new RoleCopyVO();
        String loginUserName = roleCopyDTO.getLoginUserName();
        String userId = roleCopyDTO.getUserId();
        String corpid = roleCopyDTO.getCorpid();
        Integer copyRoleId = roleCopyDTO.getCopyRoleId();

        int roleLimit = PaasConstant.ROLE_NUM_LIMIT;
        // 读取公司配置
        CompanyConfigEntity systemRoleConfig = companyConfigModel.getByConfigAlias(CompanyConfigEnum.SYSTEM_ROLE_NUM.getAlias(), corpid);
        if (!Objects.isNull(systemRoleConfig)) {
            roleLimit = Integer.valueOf(systemRoleConfig.getConfigValue());
        }

        // 判断公司自定义角色上线
        Integer roleNum = roleModel.getCorpRoleCount(corpid);
        if (roleNum >= roleLimit) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.ROLE_NUM_EXCEED);
        }

        RoleEntity roleCopy = roleModel.getByKey(copyRoleId, corpid);
        if (roleCopy == null) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.ROLE_NOT_EXIST);
        }

        RoleEntity role = new RoleEntity();
        BeanUtil.copyProperties(roleCopy, role);
        String oldRoleName = role.getRoleName();
        // 将id 置 null
        role.setId(null);
        // 设置 roleName 为原 roleName + "-复制"
        role.setRoleName(oldRoleName + "-" + I18nMessageUtil.getMessage(I18nStringConstant.COPY_SUFFIX));
        // 设置 roleAlias
        role.setRoleAlias(corpid + "_" + System.currentTimeMillis());
        // corpid不能被设置成 “0”，所以重新覆盖一次
        role.setCorpid(corpid);

        try {
            roleModel.insert(role);
            roleCopyVO.setRoleId(role.getId());
        } catch (Exception e) {
            LOG.error("RoleService 执行出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }

        // 日志
        String memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_COPY_ROLE), loginUserName, oldRoleName, role.getRoleName());
        mongoLogHelp.buildLog(corpid, userId, loginUserName, OperateModuleTypeEnum.ROLE, OperateTypeEnum.COPY,
                role.getId().toString(), role.getRoleName(), memo, roleCopyDTO.getHttpHeader());

        return roleCopyVO;
    }

    @Deprecated
    @Override
    public RoleDetailVO detail(RoleDetailDTO roleDetailDTO) throws XbbException {
        RoleDetailVO roleDetailVO = new RoleDetailVO();
        String corpid = roleDetailDTO.getCorpid();
        Integer roleId = roleDetailDTO.getRoleId();

        RoleEntity role = roleModel.getByKey(roleId, corpid);
        if (role == null) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.ROLE_NOT_EXIST);
        }

        roleDetailVO.setRoleId(roleId);
        roleDetailVO.setDataPermission(role.getDataPermission());
        roleDetailVO.setRoleName(role.getRoleName());
        roleDetailVO.setPermissions(role.getPermissions());
        //解析appPermissionWithNamePojo，传入应用名和表单/报表名
        List<AppPermissionWithNamePojo> appPermissions = JSON.parseArray(role.getPaasPermissions(), AppPermissionWithNamePojo.class);

        if (appPermissions != null && appPermissions.size() > 0) {

        }

        roleDetailVO.setPaasPermissions(appPermissions);

        return roleDetailVO;
    }

    @Override
    public RoleAppDetailVO appDetail(RoleAppDetailDTO roleAppDetailDTO) throws XbbException {
        RoleAppDetailVO roleAppDetailVO = new RoleAppDetailVO();
        String corpid = roleAppDetailDTO.getCorpid();
        Integer roleId = roleAppDetailDTO.getRoleId();

        RoleEntity role = roleModel.getByKey(roleId, corpid);
        if (role == null) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.ROLE_NOT_EXIST);
        }

        // 所有应用权限
        List<AppPermissionWithNamePojo> allAppPermissions = new ArrayList<>();

        // 将saas应用添加到所有应用权限列表中，并标记当前角色是否具有对应应用的权限
        setAllSaasAppPerms(allAppPermissions, role, corpid);
        // 将saas应用添加到所有应用权限列表中，并标记当前角色是否具有对应应用的权限
        setAllPaasAppPerms(allAppPermissions, role, corpid);
        Map<String, Object> params = new HashMap<>();
        params.put("corpid", corpid);
        params.put("aliasIn", ProPermissionAliasEnum.getAppPermissionAlias());
        params.put("del", 0);
        List<ProPermissionEntity> proPermissionEntityList = proPermissionModel.findEntitys(params);
        Map<ProPermissionAliasEnum, Integer> appIdMap = new HashMap<>();
        for (ProPermissionEntity entity : proPermissionEntityList) {
            String alias = entity.getAlias();
            ProPermissionAliasEnum proPermissionAliasEnum = ProPermissionAliasEnum.getByAlias(alias);
            if (Objects.nonNull(proPermissionAliasEnum)) {
                appIdMap.put(proPermissionAliasEnum, entity.getId());
            }
        }

        params.clear();
        params.put("corpid", corpid);
        params.put("aliasIn", SystemAppMenuEnum.getAppAliasList());
        params.put("del", 0);
        List<PaasAppEntity> saasAppList = paasAppModel.findEntitys(params);
        Map<Long, String> saasIdAndNameMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        Map<Long, Long> saasIdAndAppIdMap = new HashMap<>();
        for (PaasAppEntity paasAppEntity : saasAppList) {
            String alias = paasAppEntity.getAlias();
            SystemAppMenuEnum systemAppMenuEnum = SystemAppMenuEnum.getSystemAppMenuEnum(alias);
            if (Objects.nonNull(systemAppMenuEnum)) {
                switch (systemAppMenuEnum) {
                    case CRM:
                        saasIdAndAppIdMap.put(appIdMap.get(ProPermissionAliasEnum.CRM).longValue(), paasAppEntity.getId());
                        saasIdAndNameMap.put(appIdMap.get(ProPermissionAliasEnum.CRM).longValue(), paasAppEntity.getName());
                        break;
                    case PRODUCT:
                        saasIdAndAppIdMap.put(appIdMap.get(ProPermissionAliasEnum.PRODUCT_MANAGEMENT).longValue(), paasAppEntity.getId());
                        saasIdAndNameMap.put(appIdMap.get(ProPermissionAliasEnum.PRODUCT_MANAGEMENT).longValue(), paasAppEntity.getName());
                        break;
                    case JXC:
                        saasIdAndAppIdMap.put(appIdMap.get(ProPermissionAliasEnum.JXC).longValue(), paasAppEntity.getId());
                        saasIdAndNameMap.put(appIdMap.get(ProPermissionAliasEnum.JXC).longValue(), paasAppEntity.getName());
                        break;
                    case FUND_MANAGEMENT:
                        saasIdAndAppIdMap.put(appIdMap.get(ProPermissionAliasEnum.FUND_MANAGEMENT).longValue(), paasAppEntity.getId());
                        saasIdAndNameMap.put(appIdMap.get(ProPermissionAliasEnum.FUND_MANAGEMENT).longValue(), paasAppEntity.getName());
                        break;
                    case WORK_ORDER:
                        saasIdAndNameMap.put(appIdMap.get(ProPermissionAliasEnum.WORK_ORDER_APP).longValue(), paasAppEntity.getName());
                        break;
                    case MARKET_MANAGEMENT:
                        saasIdAndNameMap.put(appIdMap.get(ProPermissionAliasEnum.MARKET_MANAGEMENT).longValue(), paasAppEntity.getName());
                        break;
                    case CALL_CENTER:
                        break;
                    case CALL_CENTER_DU_YAN:
                        break;
                    case GROUP_MESSAGE:
                        break;
                    case SEARCH_CUSTOMER:
                        break;
                    default:
                }
            }
        }

        List<AppPermissionWithNamePojo> enableAppPermissions = JSON.parseArray(role.getPaasPermissions(), AppPermissionWithNamePojo.class);
        if (Objects.isNull(enableAppPermissions)) {
            enableAppPermissions = new ArrayList<>();
        }
        Set<Long> enableIds = new HashSet<>();
        for (AppPermissionWithNamePojo pojo : enableAppPermissions) {
            enableIds.add(pojo.getAppId());
        }
        // 工单和产品特色处理
        Map<String, String> specialName = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        specialName.put(I18nMessageUtil.getMessage(PaasConstant.WORK_ORDER_MANAGEMENT), XbbRefTypeEnum.WORK_ORDER.getName());
        specialName.put(I18nMessageUtil.getMessage(PaasConstant.PRODUCT_MANAGEMENT), XbbRefTypeEnum.PRODUCT.getName());
        for (AppPermissionWithNamePojo pojo : allAppPermissions) {
            Long appId = pojo.getAppId();
            Long paasAppId = saasIdAndAppIdMap.get(appId);
            if (enableIds.contains(paasAppId)) {
                pojo.setEnable(true);
            }
            changeNameById(saasIdAndNameMap, specialName, pojo, appId);
        }


        roleAppDetailVO.setRoleId(roleId);
        roleAppDetailVO.setDataPermission(role.getDataPermission());
        roleAppDetailVO.setAppPermissions(allAppPermissions);
        return roleAppDetailVO;
    }

    /**
     *  根据id修改名字
     * @param saasIdAndNameMap
     * @param specialName
     * @param pojo
     * @param appId
     */
    private void changeNameById(Map<Long, String> saasIdAndNameMap, Map<String, String> specialName, AppPermissionWithNamePojo pojo, Long appId) {
        String pojoName = pojo.getName();
        String appName = saasIdAndNameMap.get(appId);
        StringBuilder newName = new StringBuilder();
        if (Objects.equals(specialName.get(pojoName), appName)) {
            return;
        }
        if (StringUtil.isNotEmpty(appName) && !Objects.equals(appName, pojo.getName())) {
            newName.append(appName).append("(").append(pojo.getName()).append(")");
            pojo.setName(newName.toString());
        }
    }


    @Override
    public RoleAppDetailVO batchAppDetail(RoleAppDetailDTO roleAppDetailDTO) throws XbbException {
        RoleAppDetailVO roleAppDetailVO = new RoleAppDetailVO();
        String corpid = roleAppDetailDTO.getCorpid();
        Integer roleId = roleAppDetailDTO.getRoleId();

        RoleEntity role = roleModel.getByKey(roleId, corpid);
        if (role == null) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.ROLE_NOT_EXIST);
        }

        // 所有应用权限
        List<AppPermissionWithNamePojo> allAppPermissions = new ArrayList<>();

        // 所有能设置数据权限的 SAAS 应用
        Map<String, Object> params = new HashMap<>(8);
        params.put("parentId", 0);
        params.put("enable", 1);
        params.put("del", 0);
        params.put("aliasIn", Arrays.asList(ProPermissionAliasEnum.CRM.getAlias(), ProPermissionAliasEnum.JXC.getAlias(), ProPermissionAliasEnum.FUND_MANAGEMENT.getAlias(), ProPermissionAliasEnum.WORK_ORDER_APP.getAlias(),
                ProPermissionAliasEnum.DISTRIBUTOR_MANAGEMENT.getAlias(), ProPermissionAliasEnum.MARKET_MANAGEMENT.getAlias(), ProPermissionAliasEnum.MARKETING_MANAGEMENT.getAlias(), ProPermissionAliasEnum.WORK_ORDER_V2_CENTER.getAlias()));
        params.put("orderByStr", "sort");
        List<ProPermissionEntity> allSaasApps = proPermissionModel.findEntitys(params);

        for (ProPermissionEntity saasApp: allSaasApps) {
            AppPermissionWithNamePojo appPojo = new AppPermissionWithNamePojo();
            appPojo.setAppId(saasApp.getId().longValue());
            appPojo.setName(saasApp.getName());
            appPojo.setSaasMark(SaasMarkEnum.SAAS.getCode());
            allAppPermissions.add(appPojo);
        }

        // paas
        params.clear();
        params.put("corpid", corpid);
        params.put("del", 0);
        params.put("saasMark", 2);
        params.put("orderByStr", "sort");
        // 查询所有 PAAS 应用
        List<PaasAppEntity> allPaasApps = paasAppModel.list(params);

        Set<Long> appIds = new HashSet<>();
        for (PaasAppEntity allPaasApp : allPaasApps) {
            appIds.add(allPaasApp.getId());
        }
        // 移除没有表单的PaaS应用
        params.clear();
        params.put("corpid", corpid);
        params.put("del", DelEnum.NORMAL.getDel());
        params.put("appIdIn", appIds);
        List<PaasFormEntity> formEntityList = paasFormModel.findEntity(params);
        Set<Long> formAppIds = new HashSet<>();
        for (PaasFormEntity paasFormEntity : formEntityList) {
            formAppIds.add(paasFormEntity.getAppId());
        }
        appIds.removeAll(formAppIds);

        for (PaasAppEntity app : allPaasApps) {
            if (!appIds.isEmpty() && appIds.contains(app.getId())) {
                continue;
            }
            AppPermissionWithNamePojo appPojo = new AppPermissionWithNamePojo();
            appPojo.setAppId(app.getId());
            appPojo.setName(app.getName());
            appPojo.setSaasMark(app.getSaasMark());
            allAppPermissions.add(appPojo);
        }

        roleAppDetailVO.setRoleId(roleId);
        roleAppDetailVO.setAppPermissions(allAppPermissions);
        return roleAppDetailVO;
    }



    @Override
    public RoleModuleDetailVO moduleDetail(RoleModuleDetailDTO roleModuleDetailDTO) throws XbbException {
        RoleModuleDetailVO moduleDetailVO = new RoleModuleDetailVO();
        String corpid = roleModuleDetailDTO.getCorpid();
        Integer roleId = roleModuleDetailDTO.getRoleId();
        // saasMark为1 saas应用时，以此参数标示saas应用proPermissionId,saasMark为2 以此标示paas应用id
        Long appId = roleModuleDetailDTO.getAppId();
        Integer saasMark = roleModuleDetailDTO.getSaasMark();

        RoleEntity role = roleModel.getByKey(roleId, corpid);
        if (role == null) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.ROLE_NOT_EXIST);
        }

        // 传给前端的应用内模块权限清单
        List<ModulePermissionWithNamePojo> allModulePermissions = new ArrayList<>();
        if (saasMark.equals(SaasMarkEnum.SAAS.getCode())) {
            // 格式化saas应用模块权限，从数据库存储格式 ==> List<ModulePermissionWithNamePojo>
            formatSaasAppPermission(corpid, appId, role, allModulePermissions);
            moduleDetailVO.setSaasMark(saasMark);
        } else {
            // 格式化paas应用模块权限，从数据库存储格式 ==> List<ModulePermissionWithNamePojo>
            formatPaasAppPermission(corpid, appId, role, allModulePermissions);
            moduleDetailVO.setSaasMark(saasMark);
        }
        moduleDetailVO.setRoleId(roleId);
        moduleDetailVO.setAppId(appId);
        moduleDetailVO.setModules(allModulePermissions);
        return moduleDetailVO;
    }

    @Override
    public RoleEditNameVO editName(RoleEditNameDTO roleEditNameDTO) throws XbbException {
        RoleEditNameVO roleEditNameVO = new RoleEditNameVO();
        String loginUserName = roleEditNameDTO.getLoginUserName();
        String userId = roleEditNameDTO.getUserId();
        String corpid = roleEditNameDTO.getCorpid();
        Integer roleId = roleEditNameDTO.getRoleId();
        String roleName = roleEditNameDTO.getRoleName();

        // 兼容新建角色逻辑
        if (roleId == null) {
            int roleLimit = PaasConstant.ROLE_NUM_LIMIT;
            // 读取公司配置
            CompanyConfigEntity systemRoleConfig = companyConfigModel.getByConfigAlias(CompanyConfigEnum.SYSTEM_ROLE_NUM.getAlias(), corpid);
            if (!Objects.isNull(systemRoleConfig)) {
                roleLimit = Integer.valueOf(systemRoleConfig.getConfigValue());
            }

            // 判断公司自定义角色上限
            Integer roleNum = roleModel.getCorpRoleCount(corpid);
            if (roleNum >= roleLimit) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.ROLE_NUM_EXCEED);
            }

            // 构造新角色，空权限构造方法
            RoleEntity roleAdd = new RoleEntity(corpid, roleName);

            try {
                roleModel.insert(roleAdd);
                roleEditNameVO.setRoleId(roleAdd.getId());
            } catch (Exception e) {
                LOG.error("RoleService.editName 数据库执行出错", e);
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
            }

            // 日志
            String memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_ADD_ROLE), loginUserName, roleName);
            mongoLogHelp.buildLog(corpid, userId, loginUserName, OperateModuleTypeEnum.ROLE, OperateTypeEnum.NEW,
                    roleAdd.getId().toString(), roleAdd.getRoleName(), memo, roleEditNameDTO.getHttpHeader());

        } else {
            RoleEntity role = roleModel.getByKey(roleId, corpid);
            if (role == null) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.ROLE_NOT_EXIST);
            }
            String oldRoleName = role.getRoleName();

            // 系统角色名称不能修改
            if (role.getCorpid().equals(PaasConstant.DEFAULT_DATA_CORPID)) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.NOT_ALLOW_EDIT_SYS_ROLE);
            }
            role.setRoleName(roleName);

            try {
                roleModel.update(role);
                roleEditNameVO.setRoleId(role.getId());
            } catch (Exception e) {
                LOG.error("editName 执行出错", e);
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
            }

            // 日志
            String memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_UPDATE_NEW_ROLE), loginUserName, oldRoleName, roleName);
            mongoLogHelp.buildLog(corpid, userId, loginUserName, OperateModuleTypeEnum.ROLE, OperateTypeEnum.EDIT,
                    role.getId().toString(), role.getRoleName(), memo, roleEditNameDTO.getHttpHeader());
        }

        return roleEditNameVO;
    }

    @Override
    public RoleDataPermissionEditVO editDataPermission(RoleDataPermissionEditDTO dataPermissionEditDTO) throws XbbException {
        RoleDataPermissionEditVO dataPermissionEditVO = new RoleDataPermissionEditVO();
        String corpid = dataPermissionEditDTO.getCorpid();
        Integer roleId = dataPermissionEditDTO.getRoleId();
        Integer dataPermission = dataPermissionEditDTO.getDataPermission();

        RoleEntity role = roleModel.getByKey(roleId, corpid);
        if (role == null) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.ROLE_NOT_EXIST);
        }
        // 系统角色数据权限不能修改
        if (role.getCorpid().equals(PaasConstant.DEFAULT_DATA_CORPID)) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.NOT_ALLOW_EDIT_SYS_ROLE);
        }

        role.setDataPermission(dataPermission);

        try {
            roleModel.update(role);
            dataPermissionEditVO.setRoleId(role.getId());
        } catch (Exception e) {
            LOG.error("editDataPermission 执行出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }

        return dataPermissionEditVO;
    }

    @Override
    public BaseVO batchEditDataPermission(BatchEditDataPermissionDTO batchEditDataPermissionDTO) throws XbbException {
        BaseVO baseVO = new BaseVO();

        String corpid = batchEditDataPermissionDTO.getCorpid();
        Integer dataPermission = batchEditDataPermissionDTO.getDataPermission();
        Long roleId = batchEditDataPermissionDTO.getRoleId();
        RoleEntity role = roleModel.getByKey(roleId.intValue(), corpid);
        if (role == null) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.ROLE_NOT_EXIST);
        }
        // 系统角色数据能修改的方案
        CoverRoleEntity coverRole = null;
        if (role.getCorpid().equals(PaasConstant.DEFAULT_DATA_CORPID)) {
            /*
             * 不能修改管理员角色和老板系统角色
             */
            if (role.isAdminOrBoss()) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100092);
            }

            // 将cover_role表中的数据覆盖到role中
            coverRole = coverRoleModel.getByRoleId(role.getId(), corpid);
            if (coverRole == null) {
                coverRole = new CoverRoleEntity();
                coverRole.setCorpid(corpid);
                coverRole.setRoleId(roleId.intValue());
                coverRole.setRoleName(role.getRoleName());
            }
        }


        List<BatchEditDataPermissionAppsPojo> apps = batchEditDataPermissionDTO.getApps();

        List<Long> saasAppIds = new ArrayList<>();
        List<Long> paasAppIds = new ArrayList<>();
        for (BatchEditDataPermissionAppsPojo pojo : apps) {
            if (Objects.equals(SaasMarkEnum.SAAS.getCode(), pojo.getSaasMark())) {
                saasAppIds.add(pojo.getAppId());
            } else {
                paasAppIds.add(pojo.getAppId());
            }
        }

        // 当前设置的数据权限
        List<DataPermissionDetailPojo> nowDataPermissionDetailPojos = new ArrayList<>();

        // SaaS应用的处理
        Map<String, Object> params = new HashMap<>();
        params.put("parentIdIn", saasAppIds);
        params.put("del", 0);
        params.put("orderByStr", "parent_id,sort");
        List<ProPermissionEntity> allModules = proPermissionModel.findEntitys(params);

        // SaaS应用和表单二级封装
        Map<Long, List<Long>> saasAppIdAndFormIdsMap = new HashMap<>();
        for (ProPermissionEntity entity : allModules) {
            if (!ProPermissionAliasEnum.checkNoDataPermissionByAlias(entity.getAlias())) {
                boolean not = Objects.equals(ProPermissionAliasEnum.SERVICE_PROJECT.getAlias(), entity.getAlias())
                        && !Objects.equals(dataPermission, DataPermissionEnum.SELF.getCode())
                        && !Objects.equals(dataPermission, DataPermissionEnum.ALL.getCode());
                if (not) {
                    // 除了服务项目的个人权限和全部权限，不可以设置
                    continue;
                }
                Long parentId = entity.getParentId().longValue();
                List<Long> formIds = saasAppIdAndFormIdsMap.getOrDefault(parentId, new ArrayList<>());
                formIds.add(entity.getId().longValue());
                saasAppIdAndFormIdsMap.put(parentId, formIds);
            }
        }
        for (Map.Entry<Long, List<Long>> entry : saasAppIdAndFormIdsMap.entrySet()) {
            Long appId = entry.getKey();
            List<Long> formIds = entry.getValue();

            DataPermissionDetailPojo dataPermissionDetailPojo = new DataPermissionDetailPojo();
            dataPermissionDetailPojo.setId(appId);
            dataPermissionDetailPojo.setSaasMark(SaasMarkEnum.SAAS.getCode());

            List<DataPermissionsPojo> permissions = new ArrayList<>();
            for (Long id : formIds) {
                DataPermissionsPojo dataPermissionsPojo = new DataPermissionsPojo();
                dataPermissionsPojo.setId(id);
                dataPermissionsPojo.setSaasMark(SaasMarkEnum.SAAS.getCode());
                dataPermissionsPojo.setDataPermission(dataPermission);
                permissions.add(dataPermissionsPojo);
            }
            dataPermissionDetailPojo.setPermissions(permissions);
            nowDataPermissionDetailPojos.add(dataPermissionDetailPojo);
        }
        // SaaS应用内PaaS表单的数据权限处理
        params.clear();
        params.put("aliasIn", ProPermissionAliasEnum.getAppPermissionAlias());
        List<ProPermissionEntity> proPermissionEntityList = proPermissionModel.findEntitys(params);
        Map<Long, ProPermissionAliasEnum> permissionIdAndAliasEnumMap = new HashMap<>();
        for (ProPermissionEntity entity : proPermissionEntityList) {
            for (Long appId : saasAppIds) {
                if (Objects.equals(appId.intValue(), entity.getId())) {
                    permissionIdAndAliasEnumMap.put(appId, ProPermissionAliasEnum.getByAlias(entity.getAlias()));
                    break;
                }
            }
        }
        Set<String> appAlias = new HashSet<>();
        Map<String, Long> saasAppIdAndAppAliasMap = new HashMap();
        for (Map.Entry<Long, ProPermissionAliasEnum> enumEntry : permissionIdAndAliasEnumMap.entrySet()) {
            Long appId = enumEntry.getKey();
            ProPermissionAliasEnum proPermissionAliasEnum = enumEntry.getValue();
            switch (proPermissionAliasEnum) {
                case CRM:
                    appAlias.add(SystemAppMenuEnum.CRM.getAlias());
                    saasAppIdAndAppAliasMap.put(SystemAppMenuEnum.CRM.getAlias(), appId);
                    break;
                case JXC:
                    appAlias.add(SystemAppMenuEnum.JXC.getAlias());
                    saasAppIdAndAppAliasMap.put(SystemAppMenuEnum.JXC.getAlias(), appId);
                    break;
                case PRODUCT_MANAGEMENT:
                    appAlias.add(SystemAppMenuEnum.PRODUCT.getAlias());
                    saasAppIdAndAppAliasMap.put(SystemAppMenuEnum.PRODUCT.getAlias(), appId);
                    break;
                case FUND_MANAGEMENT:
                    appAlias.add(SystemAppMenuEnum.FUND_MANAGEMENT.getAlias());
                    saasAppIdAndAppAliasMap.put(SystemAppMenuEnum.FUND_MANAGEMENT.getAlias(), appId);
                    break;
                case WORK_ORDER_APP:
                    appAlias.add(SystemAppMenuEnum.WORK_ORDER.getAlias());
                    saasAppIdAndAppAliasMap.put(SystemAppMenuEnum.WORK_ORDER.getAlias(), appId);
                    break;
                case MARKET_MANAGEMENT:
                    appAlias.add(SystemAppMenuEnum.MARKET_MANAGEMENT.getAlias());
                    saasAppIdAndAppAliasMap.put(SystemAppMenuEnum.MARKET_MANAGEMENT.getAlias(), appId);
                    break;
                case WORK_ORDER_V2_CENTER:
                    appAlias.add(SystemAppMenuEnum.WORK_ORDER_V2_CENTER.getAlias());
                    saasAppIdAndAppAliasMap.put(SystemAppMenuEnum.WORK_ORDER_V2_CENTER.getAlias(), appId);
                    break;
                case CHART_CENTER:
                case PROCESS_APP:
                case MANAGE_CENTER:
                case SMS_APP:
                default:
                    break;
            }
        }
        if (!appAlias.isEmpty()) {
            params.clear();
            params.put("corpid", corpid);
            params.put("del", 0);
            params.put("aliasIn", appAlias);
            List<PaasAppEntity> paasAppEntityList = paasAppModel.findEntitys(params);

            Map<Long, Long> saasAppIdAndPaasAppIdMap = new HashMap<>();
            for (PaasAppEntity entity : paasAppEntityList) {
                Long saasAppId = saasAppIdAndAppAliasMap.get(entity.getAlias());
                saasAppIdAndPaasAppIdMap.put(entity.getId(), saasAppId);
            }

            List<Long> proAppIds = new ArrayList<>();
            for (PaasAppEntity entity : paasAppEntityList) {
                proAppIds.add(entity.getId());
            }
            params.clear();
            params.put("corpid",corpid);
            params.put("del", 0);
            params.put("appIdList", proAppIds);
            params.put("typeIn", Arrays.asList(2, 3, 4));
            params.put("orderByStr", "sort");
            params.put("negAliasIn", Collections.singletonList(XbbRefTypeEnum.WORK_REPORT.getAlias()));
            List<PaasMenuEntity> paasMenuEntityList = paasMenuModel.list(params);

            params.clear();
            params.put("corpid",corpid);
            params.put("del", 0);
            params.put("appIdIn", proAppIds);
            params.put("negAliasIn", Collections.singletonList(XbbRefTypeEnum.WORK_REPORT.getAlias()));
            params.put("columns", "id, corpid, app_id, menu_id, form_id, saas_mark, business_type");
            List<PaasFormExplainEntity> paasFormExplainEntityList = paasFormExplainModel.findEntitys(params);
            // 删除没有解释的菜单
            Map<Long, PaasFormExplainEntity> menuIdMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            paasFormExplainEntityList.forEach(item -> menuIdMap.put(item.getMenuId(), item));
            paasMenuEntityList.removeIf(paasMenuEntity -> !menuIdMap.containsKey(paasMenuEntity.getId()));

            Map<Long, List<Long>> paasAppIdAndFormIdsMap = new HashMap<>();
            for (PaasMenuEntity entity : paasMenuEntityList) {
                List<Long> formIds = paasAppIdAndFormIdsMap.getOrDefault(entity.getAppId(), new ArrayList<>());
                formIds.add(entity.getId());
                paasAppIdAndFormIdsMap.put(entity.getAppId(), formIds);
            }

            for (Map.Entry<Long, List<Long>> entry : paasAppIdAndFormIdsMap.entrySet()) {
                Long paasAppId = entry.getKey();
                Long saasAppId = saasAppIdAndPaasAppIdMap.get(paasAppId);
                List<Long> formIds = entry.getValue();
                for (DataPermissionDetailPojo dataPermissionDetailPojo : nowDataPermissionDetailPojos) {
                    if (Objects.equals(dataPermissionDetailPojo.getId(), saasAppId) && Objects.equals(SaasMarkEnum.SAAS.getCode(), dataPermissionDetailPojo.getSaasMark())) {

                        List<DataPermissionsPojo> permissions = new ArrayList<>();
                        for (Long id : formIds) {
                            DataPermissionsPojo dataPermissionsPojo = new DataPermissionsPojo();
                            dataPermissionsPojo.setId(id);
                            dataPermissionsPojo.setSaasMark(SaasMarkEnum.PAAS.getCode());
                            dataPermissionsPojo.setDataPermission(dataPermission);
                            permissions.add(dataPermissionsPojo);
                        }

                        dataPermissionDetailPojo.getPermissions().addAll(permissions);
                        break;
                    }
                }
            }
        }


        // PaaS应用的处理
        params.clear();
        params.put("corpid", corpid);
        params.put("appIdList", paasAppIds);
        params.put("del", 0);
        params.put("typeIn", Arrays.asList(2, 3, 4));
        params.put("orderByStr", "sort");
        List<PaasMenuEntity> paasMenuEntityList = paasMenuModel.list(params);
        Map<Long, List<Long>> paasAppIdAndMenuIdMap = new HashMap<>();
        for (PaasMenuEntity entity : paasMenuEntityList) {
            List<Long> menuIds = paasAppIdAndMenuIdMap.getOrDefault(entity.getAppId(), new ArrayList<>());
            menuIds.add(entity.getId());
            paasAppIdAndMenuIdMap.put(entity.getAppId(), menuIds);
        }

        for (Map.Entry<Long, List<Long>> entry : paasAppIdAndMenuIdMap.entrySet()) {
            Long appId = entry.getKey();
            List<Long> menuIds = entry.getValue();
            DataPermissionDetailPojo dataPermissionDetailPojo = new DataPermissionDetailPojo();
            dataPermissionDetailPojo.setId(appId);
            dataPermissionDetailPojo.setSaasMark(SaasMarkEnum.PAAS.getCode());

            List<DataPermissionsPojo> permissions = new ArrayList<>();
            for (Long id : menuIds) {
                DataPermissionsPojo dataPermissionsPojo = new DataPermissionsPojo();
                dataPermissionsPojo.setId(id);
                dataPermissionsPojo.setSaasMark(SaasMarkEnum.PAAS.getCode());
                dataPermissionsPojo.setDataPermission(dataPermission);
                permissions.add(dataPermissionsPojo);
            }
            dataPermissionDetailPojo.setPermissions(permissions);
            nowDataPermissionDetailPojos.add(dataPermissionDetailPojo);
        }


        // 保存新的数据权限
        String dataPermissionDetailStr = role.getDataPermissionDetail();
        List<DataPermissionDetailPojo> dataPermissionDetailPojos = JSON.parseArray(dataPermissionDetailStr, DataPermissionDetailPojo.class);
        if (dataPermissionDetailPojos == null) {
            dataPermissionDetailPojos = new ArrayList<>();
        }
        for (DataPermissionDetailPojo nowDataPermissionDetailPojo : nowDataPermissionDetailPojos) {
            boolean isNew = true;
            for (DataPermissionDetailPojo dataPermissionDetailPojo : dataPermissionDetailPojos) {
                if (Objects.equals(nowDataPermissionDetailPojo.getId(), dataPermissionDetailPojo.getId()) && Objects.equals(dataPermissionDetailPojo.getSaasMark(), nowDataPermissionDetailPojo.getSaasMark())) {
                    dataPermissionDetailPojo.setPermissions(nowDataPermissionDetailPojo.getPermissions());
                    isNew = false;
                    break;
                }
            }
            if (isNew) {
                dataPermissionDetailPojos.add(nowDataPermissionDetailPojo);
            }

        }

        role.setDataPermissionDetail(JSON.toJSONString(dataPermissionDetailPojos));


        try {
            if (role.getCorpid().equals(PaasConstant.DEFAULT_DATA_CORPID)) {
                coverRole.setPermissions(role.getPermissions());
                String rolePassPermission = role.getPaasPermissions() == null ? "" : role.getPaasPermissions();
                coverRole.setPaasPermissions(rolePassPermission);
                coverRole.setDataPermissionDetail(role.getDataPermissionDetail());
                coverRoleModel.save(coverRole);
            } else {
                roleModel.update(role);
            }
        } catch (Exception e) {
            LOG.error("RoleService.save 执行出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }

        return baseVO;
    }

    @Override
    public RoleSaveVO save(RoleSaveDTO roleSaveDTO) throws XbbException {
        RoleSaveVO roleSaveVO = new RoleSaveVO();
        roleSaveVO.setSysModified(false);

        String corpid = roleSaveDTO.getCorpid();
        Integer roleId = roleSaveDTO.getRoleId();
        Long appId = roleSaveDTO.getAppId();
        Integer saasMark = roleSaveDTO.getSaasMark();

        RoleEntity role = roleModel.getByKey(roleId, corpid);
        if (role == null) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.ROLE_NOT_EXIST);
        }
        // 系统角色数据能修改的方案
        CoverRoleEntity coverRole = null;
        if (role.getCorpid().equals(PaasConstant.DEFAULT_DATA_CORPID)) {
            /*
             * 不能修改管理员角色和老板系统角色
             */
            if (role.isAdminOrBoss()) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100092);
            }

            // 将cover_role表中的数据覆盖到role中
            coverRole = coverRoleModel.getByRoleId(role.getId(), corpid);
            if (coverRole == null) {
                coverRole = new CoverRoleEntity();
                coverRole.setCorpid(corpid);
                coverRole.setRoleId(roleId);
                coverRole.setRoleName(role.getRoleName());
            }
        }

        // 修改后的角色对应该应用的权限清单
        List<ModulePermissionWithNamePojo> modulePerms = roleSaveDTO.getModules();

        // TODO passPermissions 的校验

        // saas应用权限和paas应用权限保存逻辑区分
        if (saasMark.equals(SaasMarkEnum.SAAS.getCode())) {
            // saas应用权限保存逻辑
            saasPermissionSave(appId, role, modulePerms, corpid);
            dynamicSaasPermissionSave(appId, role, modulePerms, corpid);
        } else {
            // paas应用权限保存逻辑
            paasPermissionSave(appId, role, modulePerms);
            dynamicPaasPermissionSave(appId, role, modulePerms);
        }

        try {
            if (role.getCorpid().equals(PaasConstant.DEFAULT_DATA_CORPID)) {
                coverRole.setPermissions(role.getPermissions());
                String rolePassPermission = role.getPaasPermissions() == null ? "" : role.getPaasPermissions();
                coverRole.setPaasPermissions(rolePassPermission);
                coverRole.setDataPermissionDetail(role.getDataPermissionDetail());
                coverRole.setDynamicPermissions(role.getDynamicPermissions());
                coverRoleModel.save(coverRole);
                // 系统角色并修改
                roleSaveVO.setSysModified(true);
            } else {
                roleModel.update(role);
            }
            roleSaveVO.setRoleId(role.getId());
        } catch (Exception e) {
            LOG.error("RoleService.save 执行出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }

        return roleSaveVO;
    }

    private void dynamicSaasPermissionSave(Long appId, RoleEntity role, List<ModulePermissionWithNamePojo> modulePerms, String corpid) {
        // SaaS应用内PaaS表单权限保存
        Map<String, Object> params = new HashMap<>();
        params.put("id", appId);
        params.put("aliasIn", ProPermissionAliasEnum.getAppPermissionAlias());
        List<ProPermissionEntity> proApppermissionList = proPermissionModel.findEntitys(params);
        ProPermissionAliasEnum proPermissionAliasEnum = null;
        for (ProPermissionEntity entity : proApppermissionList) {
            if (Objects.equals(entity.getId(), appId.intValue())) {
                proPermissionAliasEnum = ProPermissionAliasEnum.getByAlias(entity.getAlias());
                break;
            }
        }

        String appAlias = null;
        if (Objects.nonNull(proPermissionAliasEnum)) {
            switch (proPermissionAliasEnum) {
                case CRM:
                    appAlias = SystemAppMenuEnum.CRM.getAlias();
                    break;
                case JXC:
                    appAlias = SystemAppMenuEnum.JXC.getAlias();
                    break;
                case PRODUCT_MANAGEMENT:
                    appAlias = SystemAppMenuEnum.PRODUCT.getAlias();
                    break;
                case FUND_MANAGEMENT:
                    appAlias = SystemAppMenuEnum.FUND_MANAGEMENT.getAlias();
                    break;
                case WORK_ORDER_APP:
                    appAlias = SystemAppMenuEnum.WORK_ORDER.getAlias();
                    break;
                case MARKET_MANAGEMENT:
                    appAlias = SystemAppMenuEnum.MARKET_MANAGEMENT.getAlias();
                    break;
                case CHART_CENTER:
                case PROCESS_APP:
                case MANAGE_CENTER:
                case SMS_APP:
                default:
            }
        }
        if (Objects.nonNull(appAlias)) {
            PaasAppEntity paasAppEntity = paasAppModel.getByAlias(appAlias, corpid);
            if (Objects.nonNull(paasAppEntity)) {
                Long paasAppId = paasAppEntity.getId();
                boolean findAppPerm = false;
                List<DynamicPermissionPojo> dynamicPermissions = JSON.parseArray(role.getDynamicPermissions(), DynamicPermissionPojo.class);
                if (Objects.isNull(dynamicPermissions)) {
                    dynamicPermissions = new ArrayList<>();
                }
                Iterator<DynamicPermissionPojo> appPermIterator = dynamicPermissions.iterator();
                boolean atLeastOnePerm = false;
                while (appPermIterator.hasNext()) {
                    DynamicPermissionPojo appPerm = appPermIterator.next();
                    if (!paasAppId.equals(appPerm.getAppId())) {
                        continue;
                    }
                    if (modulePerms.size() > 0) {
                        // 修改该角色对应该应用的权限
                        atLeastOnePerm = setDynamicModulePerms(appPerm, modulePerms);
                        // 没有有效权限，删除该角色对应该应用的权限
                        if (!atLeastOnePerm) {
                            appPermIterator.remove();
                        }
                    } else {
                        //删除该角色对应该应用的权限
                        appPermIterator.remove();
                    }
                    findAppPerm = true;
                    break;
                }

                // 添加权限且原来没有该应用的权限
                if (!findAppPerm) {
                    DynamicPermissionPojo dynamicPerm = new DynamicPermissionPojo();
                    dynamicPerm.setAppId(paasAppId);
                    atLeastOnePerm = setDynamicModulePerms(dynamicPerm, modulePerms);
                    if (atLeastOnePerm) {
                        dynamicPermissions.add(dynamicPerm);
                    }
                }

                role.setDynamicPermissions(JSON.toJSONString(dynamicPermissions));
            }
        }
    }

    @Override
    public RoleSaveVO saveSpecial(SaveSpecialPermissionDTO saveSpecialPermissionDTO) throws XbbException {
        RoleSaveVO roleSaveVO = new RoleSaveVO();
        roleSaveVO.setSysModified(false);

        Long roleId = saveSpecialPermissionDTO.getRoleId();
        String corpid = saveSpecialPermissionDTO.getCorpid();
        RoleEntity role = roleModel.getByKey(roleId.intValue(), corpid);
        if (role == null) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.ROLE_NOT_EXIST);
        }
        // 系统角色数据能修改的方案
        CoverRoleEntity coverRole = null;
        if (role.getCorpid().equals(PaasConstant.DEFAULT_DATA_CORPID)) {
            /*
             * 不能修改管理员角色和老板系统角色
             */
            if (role.isAdminOrBoss()) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100092);
            }

            // 将cover_role表中的数据覆盖到role中
            coverRole = coverRoleModel.getByRoleId(role.getId(), corpid);
            if (coverRole == null) {
                coverRole = new CoverRoleEntity();
                coverRole.setCorpid(corpid);
                coverRole.setRoleId(roleId.intValue());
                coverRole.setRoleName(role.getRoleName());
            }
        }

        Integer dataPermission = saveSpecialPermissionDTO.getDataPermission();
        String dataPermissionDetailStr = role.getDataPermissionDetail();
        List<DataPermissionDetailPojo> dataPermissionDetailPojos = JSON.parseArray(dataPermissionDetailStr, DataPermissionDetailPojo.class);
        if (dataPermissionDetailPojos == null) {
            dataPermissionDetailPojos = new ArrayList<>();
        }

        Map<String, Object> params = new HashMap<>();
        params.put("aliasIn", Arrays.asList(ProPermissionAliasEnum.MANAGE_CENTER.getAlias(), ProPermissionAliasEnum.ORGANIZATION_SET.getAlias()));
        List<ProPermissionEntity> proPermissionEntityList = proPermissionModel.findEntitys(params);
        Long appId = null;
        Long menuId = null;
        for (ProPermissionEntity entity : proPermissionEntityList) {
            if (Objects.equals(entity.getAlias(), ProPermissionAliasEnum.MANAGE_CENTER.getAlias())) {
                appId = entity.getId().longValue();
            }
            if (Objects.equals(entity.getAlias(), ProPermissionAliasEnum.ORGANIZATION_SET.getAlias())) {
                menuId = entity.getId().longValue();
            }
        }
        List<DataPermissionsPojo> newDataPermissions = new ArrayList<>();
        DataPermissionsPojo dataPermissionsPojo = new DataPermissionsPojo();
        dataPermissionsPojo.setId(menuId);
        dataPermissionsPojo.setSaasMark(SaasMarkEnum.SAAS.getCode());
        dataPermissionsPojo.setDataPermission(dataPermission);
        newDataPermissions.add(dataPermissionsPojo);

        boolean isNew = true;
        for (DataPermissionDetailPojo dataPermissionDetailPojo : dataPermissionDetailPojos) {
            if (Objects.equals(dataPermissionDetailPojo.getId(), appId) && Objects.equals(dataPermissionDetailPojo.getSaasMark(), SaasMarkEnum.SAAS.getCode())) {
                dataPermissionDetailPojo.setPermissions(newDataPermissions);
                isNew = false;
            }
        }
        if (isNew) {
            DataPermissionDetailPojo newDataPermissionDetailPojo = new DataPermissionDetailPojo();
            newDataPermissionDetailPojo.setId(appId);
            newDataPermissionDetailPojo.setSaasMark(SaasMarkEnum.SAAS.getCode());
            newDataPermissionDetailPojo.setPermissions(newDataPermissions);
            dataPermissionDetailPojos.add(newDataPermissionDetailPojo);
        }

        role.setDataPermissionDetail(JSON.toJSONString(dataPermissionDetailPojos));

        try {
            if (role.getCorpid().equals(PaasConstant.DEFAULT_DATA_CORPID)) {
                coverRole.setPermissions(role.getPermissions());
                String rolePassPermission = role.getPaasPermissions() == null ? "" : role.getPaasPermissions();
                coverRole.setPaasPermissions(rolePassPermission);
                coverRole.setDataPermissionDetail(role.getDataPermissionDetail());
                coverRoleModel.save(coverRole);
                // 系统角色并修改
                roleSaveVO.setSysModified(true);
            } else {
                roleModel.update(role);
            }
            roleSaveVO.setRoleId(role.getId());
        } catch (Exception e) {
            LOG.error("RoleService.saveSpecial 执行出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }

        return roleSaveVO;
    }

    @Override
    public DetailSpecialPermissionVO detailSpecial(DetailSpecialPermissionDTO detailSpecialPermissionDTO) throws XbbException {
        DetailSpecialPermissionVO detailSpecialPermissionVO = new DetailSpecialPermissionVO();

        Long roleId = detailSpecialPermissionDTO.getRoleId();
        String corpid = detailSpecialPermissionDTO.getCorpid();
        RoleEntity role = roleModel.getByKey(roleId.intValue(), corpid);
        if (role == null) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.ROLE_NOT_EXIST);
        }

        Integer dataPermission = role.getDataPermission();
        String dataPermissionDetailStr = role.getDataPermissionDetail();
        List<DataPermissionDetailPojo> dataPermissionDetailPojos = JSON.parseArray(dataPermissionDetailStr, DataPermissionDetailPojo.class);
        if (dataPermissionDetailPojos == null) {
            dataPermissionDetailPojos = new ArrayList<>();
        }

        Map<String, Object> params = new HashMap<>();
        params.put("aliasIn", Arrays.asList(ProPermissionAliasEnum.MANAGE_CENTER.getAlias(), ProPermissionAliasEnum.ORGANIZATION_SET.getAlias()));
        List<ProPermissionEntity> proPermissionEntityList = proPermissionModel.findEntitys(params);
        Long appId = null;
        Long menuId = null;
        for (ProPermissionEntity entity : proPermissionEntityList) {
            if (Objects.equals(entity.getAlias(), ProPermissionAliasEnum.MANAGE_CENTER.getAlias())) {
                appId = entity.getId().longValue();
            }
            if (Objects.equals(entity.getAlias(), ProPermissionAliasEnum.ORGANIZATION_SET.getAlias())) {
                menuId = entity.getId().longValue();
            }
        }

        for (DataPermissionDetailPojo dataPermissionDetailPojo : dataPermissionDetailPojos) {
            if (Objects.equals(dataPermissionDetailPojo.getId(), appId) && Objects.equals(dataPermissionDetailPojo.getSaasMark(), SaasMarkEnum.SAAS.getCode())) {
                List<DataPermissionsPojo> permissions = dataPermissionDetailPojo.getPermissions();
                for (DataPermissionsPojo permission : permissions) {
                    if (Objects.equals(permission.getId(), menuId) && Objects.equals(permission.getSaasMark(), SaasMarkEnum.SAAS.getCode())) {
                        dataPermission = permission.getDataPermission();
                        break;
                    }
                }
                break;
            }
        }


        detailSpecialPermissionVO.setRoleId(roleId);
        detailSpecialPermissionVO.setDataPermission(dataPermission);
        return detailSpecialPermissionVO;
    }

    @Override
    public BaseVO recovery(RoleRecoveryDTO roleRecoveryDTO) throws XbbException {
        String corpid = roleRecoveryDTO.getCorpid();
        Integer roleId = roleRecoveryDTO.getRoleId();

        RoleEntity role = roleModel.getByKey(roleId, corpid);
        if (role == null) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.ROLE_NOT_EXIST);
        }
        if (role.getCorpid().equals(PaasConstant.DEFAULT_DATA_CORPID)) {
            CoverRoleEntity coverRole = coverRoleModel.getByRoleId(role.getId(), corpid);
            if (coverRole != null) {
                coverRoleModel.deleteByKey(coverRole.getId(), corpid);
            }
        } else {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100093);
        }

        return new BaseVO();
    }

    @Override
    public BaseVO batchAppendOrDeletePermissions(RoleAppendOrDeleteDTO roleAppendDTO) {
        List<String> copridList = roleAppendDTO.getCorpidList();
        if (CollectionUtils.isEmpty(copridList)){
            return new BaseVO();
        }
        String replaceRole;
        if (Objects.equals(roleAppendDTO.getReplaceRoleId(),-1)){
            replaceRole =  "";
        }else {
            replaceRole =  "|" + roleAppendDTO.getReplacedRoleId() +"|" + roleAppendDTO.getReplaceRoleId();
        }
        String replacedRole = "|" + roleAppendDTO.getReplacedRoleId();
        roleModel.batchAppendPermissions(replaceRole,replacedRole,copridList);
        return new BaseVO();
    }

    //==================== private method ====================

    /**
     * 根据前端传的 List<ModulePermissionWithNamePojo> 构建数据库存储的 private List<ModulePermissionPojo>
     * @param appPerm     对应应用的权限
     * @param modulePerms 前端传过来的应用内模块权限
     * @return 返回 true 表示appPerm中至少有一项权限被开启，返回false则表示appPerm中所有权限都被关闭，
     * 说明当前的应用权限（某个角色设置）都已经被清空
     */
    private boolean setModulePerms(AppPermissionPojo appPerm, List<ModulePermissionWithNamePojo> modulePerms) {
        if (modulePerms == null || modulePerms.size() <= 0) {
            return false;
        }
        List<DynamicPermissionPojo> dynamicPermissions = new ArrayList<>();

        List<ModulePermissionPojo> modules = new ArrayList<>();
        // 为解决应用内所有表单权限置空后，应用权限也置空逻辑
        boolean atLeastOnePerm = false;
        for (ModulePermissionWithNamePojo modulePerm : modulePerms) {
            if (Boolean.TRUE.equals(modulePerm.getEnable())) {

                if (cloudCodeHelp.isCloudCodeAlias(modulePerm.getAlias())) {
                    atLeastOnePerm = true;
                    //云叩菜单
                    DynamicPermissionSubPojo dynamicPermissionSubPojo = new DynamicPermissionSubPojo();
//                    dynamicPermissionSubPojo.setFormId();
                    dynamicPermissionSubPojo.setAlias(modulePerm.getAlias());
                    dynamicPermissionSubPojo.setName(modulePerm.getName());
                    List<DynamicPermissionSubPojo> dynamicPermissionSubs = new ArrayList<>();
                    dynamicPermissionSubs.add(dynamicPermissionSubPojo);
                    DynamicPermissionPojo dynamicPermission = new DynamicPermissionPojo();
                    dynamicPermission.setModules(dynamicPermissionSubs);
                    dynamicPermissions.add(dynamicPermission);
                    continue;
                }

                atLeastOnePerm = true;
                ModulePermissionPojo module = new ModulePermissionPojo();
                BeanUtil.copyProperties(modulePerm, module);
                // 转换 List<PermissionComplexTermPojo> ==> PermissionTermsPojo
                PermissionTermsPojo termsPojo = new PermissionTermsPojo();
                List<PermissionComplexTermPojo> complexTermPojos = modulePerm.getPermission();
                if (complexTermPojos != null && complexTermPojos.size() > 0) {
                    for (PermissionComplexTermPojo complexTermPojo : complexTermPojos) {
                        if (cloudCodeHelp.isCloudCodeAlias(complexTermPojo.getAlias())) {
                            //云叩权限
                            DynamicPermissionSubPojo dynamicPermissionSubPojo = new DynamicPermissionSubPojo();
//                            dynamicPermissionSubPojo.setFormId();
                            dynamicPermissionSubPojo.setAlias(complexTermPojo.getAlias());
                            dynamicPermissionSubPojo.setName(complexTermPojo.getName());
                            List<DynamicPermissionSubPojo> dynamicPermissionSubs = new ArrayList<>();
                            dynamicPermissionSubs.add(dynamicPermissionSubPojo);
                            DynamicPermissionPojo dynamicPermission = new DynamicPermissionPojo();
                            dynamicPermission.setModules(dynamicPermissionSubs);
                            dynamicPermissions.add(dynamicPermission);
                            continue;
                        }

                        //正常权限
                        if (complexTermPojo.getValue().equals(1)) {
                            ReflectHelper.valueSet(termsPojo, complexTermPojo.getAlias(), 1);
                        }
                    }
                }
                module.setPermission(termsPojo);
                modules.add(module);
            }
        }
        if (atLeastOnePerm) {
            appPerm.setModules(modules);
        }
        return atLeastOnePerm;
    }

    /**
     * 将saas应用添加到所有应用权限列表中，并标记当前角色是否具有对应应用的权限
     * @param allAppPermissions 所有应用权限
     * @param role 对应的角色
     * @param corpid 公司id
     */
    private void setAllSaasAppPerms(List<AppPermissionWithNamePojo> allAppPermissions, RoleEntity role, String corpid) {
        // 所有SAAS 应用
        Map<String, Object> params = new HashMap<>(8);
        params.put("parentId", 0);
        params.put("enable", 1);
        params.put("del", 0);
        params.put("orderByStr", "sort");
        List<ProPermissionEntity> allSaasApps = proPermissionModel.findEntitys(params);

        PaasAppEntity paasApp = paasAppModel.getByAlias(SystemAppMenuEnum.EXPENSE_MANAGEMENT.getAlias(), corpid);

        if (Objects.isNull(paasApp) || !Objects.equals(paasApp.getEnable(), EnableEnum.OPEN.getCode())) {
            for (ProPermissionEntity proPermission : allSaasApps) {
                if (Objects.equals(proPermission.getAlias(), SystemAppMenuEnum.EXPENSE_MANAGEMENT.getAlias())) {
                    allSaasApps.remove(proPermission);
                    break;
                }
            }
        }

        // 已设置权限
        Set<Integer> permissionIdsSet = role.getPermissionIdsSet();
        for (ProPermissionEntity saasApp: allSaasApps) {
            AppPermissionWithNamePojo appPojo = new AppPermissionWithNamePojo();
            appPojo.setAppId(saasApp.getId().longValue());
            appPojo.setName(saasApp.getName());
            appPojo.setSaasMark(SaasMarkEnum.SAAS.getCode());
            if (role.isAdminOrBoss() || permissionIdsSet.contains(saasApp.getId())) {
                appPojo.setEnable(true);
            } else {
                appPojo.setEnable(false);
            }
            allAppPermissions.add(appPojo);
        }
    }

    /**
     * 将paas应用添加到所有应用权限列表中，并标记当前角色是否具有对应应用的权限
     * @param allAppPermissions 所有应用权限
     * @param role 对应的角色
     */
    private void setAllPaasAppPerms(List<AppPermissionWithNamePojo> allAppPermissions, RoleEntity role, String corpid) {
        Map<String, Object> params = new HashMap<>(8);
        params.put("corpid", corpid);
        params.put("del", 0);
        params.put("saasMark", 2);
        params.put("orderByStr", "sort");
        // 查询所有 PAAS 应用
        List<PaasAppEntity> allPaasApps = paasAppModel.list(params);

        // 解析appPermissionWithNamePojo，传入应用名和表单/报表名
        List<AppPermissionWithNamePojo> enableAppPermissions = JSON.parseArray(role.getPaasPermissions(), AppPermissionWithNamePojo.class);
        if (enableAppPermissions == null) {
            // 兼容数据库中为空的情况
            enableAppPermissions = new ArrayList<>();
        }
        // 转化为有权限的appId Set
        Set<Long> enableAppIds = new HashSet<>();
        for (AppPermissionWithNamePojo enableApp : enableAppPermissions) {
            enableAppIds.add(enableApp.getAppId());
        }

        for (PaasAppEntity app : allPaasApps) {
            AppPermissionWithNamePojo appPojo = new AppPermissionWithNamePojo();
            appPojo.setAppId(app.getId());
            appPojo.setName(app.getName());
            appPojo.setSaasMark(app.getSaasMark());
            if (role.isAdminOrBoss() || enableAppIds.contains(app.getId())) {
                appPojo.setEnable(true);
            } else {
                appPojo.setEnable(false);
            }
            allAppPermissions.add(appPojo);
        }
    }

    /**
     * 格式化saas应用模块权限，从数据库存储格式 ==> List<ModulePermissionWithNamePojo>
     * @param corpid 公司id
     * @param appId paas应用id
     * @param role 对应角色
     * @param allModulePermissions 格式化后的数据会存储在此队列
     */
    private void formatSaasAppPermission(String corpid, Long appId, RoleEntity role, List<ModulePermissionWithNamePojo> allModulePermissions)  throws XbbException {
        // SAAS应用，传输的appId为SAAS应用对应proPermissionId
        Map<String, Object> params = new HashMap<>(16);
        params.put("routerStart", appId);
        params.put("del", 0);
        params.put("orderByStr", "parent_id,sort");
        List<ProPermissionEntity> allModules = proPermissionModel.findEntitys(params);

        List<Integer> saasNoDataPermissionIds = new ArrayList<>();
        // 拆解为两部分，模块权限和模块内权限，构建父子权限
        Map<Integer, ProPermissionEntity> modulePermMap = new LinkedHashMap<>(16);
        //该公司是否开启公海高级模式
        boolean isCustomerSeniorMode = commonHelp.isCustomerPublicPoolSeniorModel(corpid);
        boolean isClueSeniorMode = commonHelp.isCluePublicPoolSeniorModel(corpid);

        Iterator<ProPermissionEntity> iterator = allModules.iterator();
        //获取套餐类型
        Integer feeType = packageHelp.getFeeType(corpid);
        //获取公司创建时间
        CompanyEntity company = companyModel.getByKey(corpid);
        //非旗舰版
        boolean unUltimate = !Objects.equals(feeType, PackageTypeEnum.ULTIMATE.getType());
        //非旗舰版要隐藏的权限
        List<String> ultimatePermisionList = ProPermissionAliasEnum.ultimatePermision();
        while (iterator.hasNext()){
            ProPermissionEntity proPermission = iterator.next();
            String alias = proPermission.getAlias();
            if (unUltimate && ultimatePermisionList.contains(alias)){
                iterator.remove();
                continue;
            }
            //如果是标准版去除智能补货
            if (Objects.equals(feeType,PackageTypeEnum.STANDARD.getType()) && Objects.equals(proPermission.getAlias(),ProPermissionAliasEnum.SMART_REPLENISHMENT.getAlias())){
                iterator.remove();
                continue;
            }
            //如果是标准版去除知识库
            if (Objects.equals(feeType,PackageTypeEnum.STANDARD.getType()) && Objects.equals(proPermission.getAlias(),ProPermissionAliasEnum.KNOWLEDGE_BASE.getAlias())){
                iterator.remove();
                continue;
            }
            //判断有无AI套餐，没有套餐，AI权限隐藏
            if (Objects.equals(proPermission.getAlias(), ProPermissionAliasEnum.AI_CENTER.getAlias())){
                IsActiveAIComboVO isActiveAIComboVO = isActiveAICombo(corpid);
                if (!isActiveAIComboVO.getIsExpired()){
                    iterator.remove();
                    continue;
                }
            }
            if (company != null) {
                if (company.getAddTime() > BasicConstant.JXC_ONLINE_DATE) {
                    if (Objects.equals(feeType,PackageTypeEnum.STANDARD.getType()) && (Objects.equals(proPermission.getAlias(),ProPermissionAliasEnum.ORDER_ON_PIN.getAlias()) || Objects.equals(proPermission.getAlias(),ProPermissionAliasEnum.PENDING_OUTSTOCK.getAlias()) || Objects.equals(proPermission.getAlias(),ProPermissionAliasEnum.PENDING_INSTOCK.getAlias()))){
                        iterator.remove();
                        continue;
                    }
                }
            }
            //TODO 数据连接移除
            if (!dataConnectionService.tplusEnable(corpid) && Objects.equals(alias,ProPermissionAliasEnum.DATA_CONNECTION.getAlias())) {
                iterator.remove();
                continue;
            }
            //老的公海池规则和公海池分组权限去除
            if(Objects.equals(proPermission.getAlias(),ProPermissionAliasEnum.PUBLIC_SET.getAlias()) || Objects.equals(proPermission.getAlias(),ProPermissionAliasEnum.PUBLIC_GROUP_SET.getAlias())){
                iterator.remove();
                continue;
            }
            //客户变更公海分组
            boolean changeCustomerPublicGroup = !isCustomerSeniorMode && Objects.equals(proPermission.getAlias(),ProPermissionAliasEnum.CUSTOMER_SWITCH_PUBLIC_GROUP.getAlias());
            if (changeCustomerPublicGroup){
                iterator.remove();
                continue;
            }
            //线索变更公海分组
            boolean changeCluePublicGroup = !isClueSeniorMode && Objects.equals(proPermission.getAlias(),ProPermissionAliasEnum.CLUE_SWITCH_PUBLIC_GROUP.getAlias());
            if (changeCluePublicGroup){
                iterator.remove();
                continue;
            }

            if (proPermission.getParentId().equals(appId.intValue())) {
                modulePermMap.put(proPermission.getId(), proPermission);
            }
            if (ProPermissionAliasEnum.checkNoDataPermissionByAlias(alias)) {
                saasNoDataPermissionIds.add(proPermission.getId());
            }
        }
        // 第二次循环，设置childList
        for (ProPermissionEntity proPermission : allModules) {
            if (proPermission.getParentId().equals(appId.intValue())) {
                continue;
            }
            ProPermissionEntity parentPermission = modulePermMap.get(proPermission.getParentId());
            if (parentPermission == null) {
                continue;
            }
            List<ProPermissionEntity> childList = parentPermission.getChildList();
            if (childList == null) {
                childList = new ArrayList<>();
            }
            childList.add(proPermission);
            parentPermission.setChildList(childList);
        }

        // 已设置的权限列表
        Set<Integer> permissionIdsSet = role.getPermissionIdsSet();
        // 已设置的数据权限
        String dataPermissionDetailStr = role.getDataPermissionDetail();
        List<DataPermissionDetailPojo> dataPermissionDetailPojos = JSON.parseArray(dataPermissionDetailStr, DataPermissionDetailPojo.class);
        if (dataPermissionDetailPojos == null) {
            dataPermissionDetailPojos = new ArrayList<>();
        }

        List<DataPermissionsPojo> permissions = new ArrayList<>();
        for (DataPermissionDetailPojo pojo : dataPermissionDetailPojos) {
            if (Objects.equals(appId, pojo.getId())) {
                permissions = pojo.getPermissions();
            }
        }
        Map<Long, Integer> saasDataPermissionMap = new HashMap<>();
        Map<Long, Integer> paasDataPermissionMap = new HashMap<>();
        for (DataPermissionsPojo pojo : permissions) {
            if (Objects.equals(SaasMarkEnum.SAAS.getCode(), pojo.getSaasMark())) {
                saasDataPermissionMap.put(pojo.getId(), pojo.getDataPermission());
            } else {
                paasDataPermissionMap.put(pojo.getId(), pojo.getDataPermission());
            }
        }
        // 模块数据权限,拼装数据
        List<PermissionComplexTermPojo> modulePerms;
        // 需要处理未开通搜客或开通搜客试用套餐的公司不允许在管理中心里展示“搜客-权限管理”
        SearchCustomerCompanyEntity soukeEntity = searchCustomerCompanyModel.getByCorpid(corpid, SoukeMealEnum.SOUKE.getType());
        boolean soukeFlag = (soukeEntity == null) || (soukeEntity.getExtraExpiry() - soukeEntity.getAddTime() < 4 * RedisConstant.LONG_DURATION);
        // 需要处理未开通精线索的套餐，未开通不展示
        FineClueCompanyEntity fineClueCompanyEntity = fineClueCompanyModel.getByCorpid(corpid, FineClueEnum.FINE_CLUE.getType());
        boolean fineClueFlag = (fineClueCompanyEntity == null) || (fineClueCompanyEntity.getExtraExpiry() <= DateUtil.getInt());
        if (soukeFlag&&fineClueFlag) {
            // 移除搜客
            modulePermMap.remove(428);
        }
        Boolean esignEnable = true;
        PaasAppEntity esignApp = paasAppModel.getByAlias(SystemAppMenuEnum.ESIGN.getAlias(), corpid);
        if (Objects.isNull(esignApp) || Objects.equals(esignApp.getEnable(), BasicConstant.ZERO)) {
            esignEnable = false;
        }

        // SaaS应用内PaaS表单处理
        params.clear();
        params.put("aliasIn", ProPermissionAliasEnum.getAppPermissionAlias());
        List<ProPermissionEntity> proPermissionEntityList = proPermissionModel.findEntitys(params);
        ProPermissionAliasEnum proPermissionAliasEnum = null;
        for (ProPermissionEntity entity : proPermissionEntityList) {
            if (Objects.equals(entity.getId(), appId.intValue())) {
                proPermissionAliasEnum = ProPermissionAliasEnum.getByAlias(entity.getAlias());
                break;
            }
        }
        String appAlias = null;
        if (!Objects.isNull(proPermissionAliasEnum)) {
            switch (proPermissionAliasEnum) {
                case CRM:
                    appAlias = SystemAppMenuEnum.CRM.getAlias();
                    break;
                case JXC:
                    appAlias = SystemAppMenuEnum.JXC.getAlias();
                    break;
                case PRODUCT_MANAGEMENT:
                    appAlias = SystemAppMenuEnum.PRODUCT.getAlias();
                    break;
                case FUND_MANAGEMENT:
                    appAlias = SystemAppMenuEnum.FUND_MANAGEMENT.getAlias();
                    // 对账单列表操作：提醒确认，代客确认，重新生成 在开通经销商后才展示
                    PaasFormEntityExt customerStatementStatisticForm = paasFormModel.getByBusinessType4Distributor(XbbRefTypeEnum.CUSTOMER_STATEMENT_STATISTIC.getCode(), corpid, DistributorMarkEnum.DISTRIBUTOR.getCode(), null);
                    if (Objects.isNull(customerStatementStatisticForm)) {
                        // 801: 对账单列表  804：提醒确认  805：代客确认  807：重新生成
                        ProPermissionEntity proPermissionEntity = modulePermMap.get(801);
                        List<ProPermissionEntity> childList = proPermissionEntity.getChildList();
                        childList.removeIf(item -> Objects.equals(item.getId(),804) || Objects.equals(item.getId(),805) || Objects.equals(item.getId(),807));
                    }
                    break;
                case WORK_ORDER_APP:
                    appAlias = SystemAppMenuEnum.WORK_ORDER.getAlias();
                    break;
                case MARKET_MANAGEMENT:
                    appAlias = SystemAppMenuEnum.MARKET_MANAGEMENT.getAlias();
                    break;
                case CHART_CENTER:
                case PROCESS_APP:
                case MANAGE_CENTER:
                case SMS_APP:
                case ORDER_CENTER:
                    appAlias = SystemAppMenuEnum.ORDER_CENTER.getAlias();
                    break;
                case MARKETING_MANAGEMENT:
                    appAlias = SystemAppMenuEnum.MARKETING_MANAGEMENT.getAlias();
                    break;
                case DISTRIBUTOR_MANAGEMENT:
                    appAlias = SystemAppMenuEnum.DISTRIBUTOR.getAlias();
                    break;
                case WORK_ORDER_V2_CENTER:
                    appAlias = SystemAppMenuEnum.WORK_ORDER_V2_CENTER.getAlias();
                    break;
                default:
            }
        }
        Map<String, String> paasAliasToName = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        List<ModulePermissionWithNamePojo> allPaasPermissions = new ArrayList<>();
        if (!Objects.isNull(appAlias)) {
            PaasAppEntity paasAppEntity = paasAppModel.getByAlias(appAlias, corpid);
            if (Objects.nonNull(paasAppEntity)) {
                Long paasAppId = paasAppEntity.getId();
                params.clear();
                params.put("corpid",corpid);
                params.put("del", 0);
                params.put("appId", paasAppId);
                params.put("orderByStr", "sort");
                params.put("negAliasIn", Collections.singletonList(XbbRefTypeEnum.WORK_REPORT.getAlias()));
                List<PaasMenuEntity> paasMenuEntities = paasMenuModel.list(params);
                List<PaasMenuEntity> paasMenuEntityList = new ArrayList<>();
                paasMenuEntities.forEach(item -> {
                    if (Objects.equals(item.getSaasMark(), SaasMarkEnum.SAAS.getCode()) && StringUtil.isNotEmpty(item.getAlias())) {
                        paasAliasToName.put(item.getAlias(), item.getName());
                    }
                    if (Arrays.asList(2, 3, 4).contains(item.getType())) {
                        paasMenuEntityList.add(item);
                    }
                });
                params.clear();
                params.put("corpid",corpid);
                params.put("del", 0);
                params.put("appId", paasAppId);
                params.put("negAliasIn", Collections.singletonList(XbbRefTypeEnum.WORK_REPORT.getAlias()));
                params.put("saasMark", SaasMarkEnum.PAAS.getCode());
                List<PaasFormExplainEntity> paasFormExplainEntityList = paasFormExplainModel.list(params);
                // 删除没有解释的菜单
                Map<Long, PaasFormExplainEntity> menuIdMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                paasFormExplainEntityList.forEach(item -> menuIdMap.put(item.getMenuId(), item));
                paasMenuEntityList.removeIf(paasMenuEntity -> (!menuIdMap.containsKey(paasMenuEntity.getId()) && !cloudCodeHelp.isCloudCodeAlias(paasMenuEntity.getAlias())));

                List<AppPermissionPojo> enableAppPermissions = JSON.parseArray(role.getPaasPermissions(), AppPermissionPojo.class);
                AppPermissionPojo thisApp = null;
                if (enableAppPermissions == null) {
                    enableAppPermissions = new ArrayList<>();
                }
                for (AppPermissionPojo enableApp : enableAppPermissions) {
                    if (Objects.equals(enableApp.getAppId(), paasAppId)) {
                        thisApp = enableApp;
                        break;
                    }
                }

                Map<Long, ModulePermissionPojo> enableModules = new HashMap<>();
                if (!Objects.isNull(thisApp) && !Objects.isNull(thisApp.getModules())) {
                    for (ModulePermissionPojo enableModule : thisApp.getModules()) {
                        enableModules.put(enableModule.getId(), enableModule);
                    }
                }
                List<PermissionComplexTermPojo> modulePaasPerms = new ArrayList<>();
                for (PaasMenuEntity module : paasMenuEntityList) {
                    Long id = module.getId();
                    if (!cloudCodeHelp.isCloudCodeAlias(module.getAlias())) {
                        modulePaasPerms = PermissionHelp.initDefaultPaasModulePermission();
                        removePaasEsignPermission(esignEnable, modulePaasPerms);
                    }
                    cloudCodeHelp.addCloudCodePermission(module.getCorpid(), module.getAppId(), module.getId(), modulePaasPerms);
                    ModulePermissionWithNamePojo modulePojo = new ModulePermissionWithNamePojo();
                    modulePojo.setId(id);
                    modulePojo.setName(module.getName());
                    modulePojo.setType(module.getType());
                    modulePojo.setSaasMark(SaasMarkEnum.PAAS.getCode());

                    if (!StringUtil.isEmpty(module.getAlias())) {
                        modulePojo.setAlias(module.getAlias());
                    }

                    // 默认设为 false, PermissionTermsPojo初始化,没有设置数据时传回初始值
                    modulePojo.setEnable(false);

                    // 超级管理员和老板默认有所有paas权限
                    if (role.isAdminOrBoss()) {
                        modulePojo.setEnable(true);
                        for (PermissionComplexTermPojo termPojo : modulePaasPerms) {
                            termPojo.setValue(1);
                        }
                    } else if (enableModules.containsKey(id)) {
                        ModulePermissionPojo enableModule = enableModules.get(id);
                        if (enableModule != null) {
                            modulePojo.setEnable(true);
                            PermissionTermsPojo enableModulePerms = enableModule.getPermission();
                            for (PermissionComplexTermPojo termPojo : modulePaasPerms) {
                                if (Objects.equals(ReflectHelper.valueGet(enableModulePerms, termPojo.getAlias()), 1)
                                || cloudCodeHelp.hasCloudCodePermissions(termPojo.getAlias(), role.getDynamicPermissions())) {
                                    termPojo.setValue(1);
                                } else {
                                    termPojo.setValue(0);
                                }
                            }
                        }
                    }

                    setEnableByDynamicPermissions(modulePojo, role.getDynamicPermissions());

                    modulePojo.setPermission(modulePaasPerms);
                    if (paasDataPermissionMap.containsKey(id)) {
                        modulePojo.setDataPermission(paasDataPermissionMap.get(id));
                    } else {
                        modulePojo.setDataPermission(role.getDataPermission());
                    }
                    allPaasPermissions.add(modulePojo);
                }
            }
        }
        BasePackageInfoVO basePackageInfoVO = packageService.getBasePackageInfoFromRedis(corpid);
        Set<String> dynamicPermissionSet = cloudCodeHelp.getDynamicPermissionSet(role.getDynamicPermissions());
        List<String> list = Arrays.asList(ProPermissionAliasEnum.DEVELOPER.getAlias(), ProPermissionAliasEnum.SERVICE_REGISTER.getAlias());
        boolean isOpenWorkflow = commonHelp.isOpenWorkFlow(corpid);
        for (ProPermissionEntity module : modulePermMap.values()) {
            removeSaasEsignPermission(esignEnable, module);
            // 移除低代码设置
            if (!Objects.equals(PackageTypeEnum.ULTIMATE.getType(), basePackageInfoVO.getFeeType())&& list.contains(module.getAlias())) {
                continue;
            }
            long id = module.getId().longValue();
            // 初始化默认paas模块权限
            modulePerms = PermissionHelp.initDefaultSaasModulePermission(module);
            if (!isOpenWorkflow) {
                // 移除掉工作流删除
                modulePerms.removeIf(item-> Objects.equals(ProPermissionAliasEnum.WORKFLOW_DELETE.getAlias(), item.getAlias()));
            }
            cloudCodeHelp.addCloudCodePermission(corpid, module.getAlias(), modulePerms);
            ModulePermissionWithNamePojo modulePojo = new ModulePermissionWithNamePojo();
            // 根据alias修改名称
            changeNameByAlias(paasAliasToName, module, id, modulePojo);
            if (isOpenWorkflow && Objects.equals(module.getAlias(), ProPermissionAliasEnum.PROCESS_SET.getAlias())) {
                modulePojo.setName(ControlCenterMenuEnum.WORK_FLOW.getName());
            }
            modulePojo.setType(ModuleTypeEnum.SAAS.getCode());
            modulePojo.setSaasMark(SaasMarkEnum.SAAS.getCode());
            // 默认设为 module的数据库值, PermissionTermsPojo初始化,没有设置数据时传回初始值
            boolean moduleEnable = permissionIdsSet.contains(module.getId());
            modulePojo.setEnable(moduleEnable);

            if (permissionIdsSet.size() > 0) {
                for (PermissionComplexTermPojo termPojo : modulePerms) {

                    if (cloudCodeHelp.isCloudCodeAlias(termPojo.getAlias())) {
                        if (role.isAdminOrBoss() || dynamicPermissionSet.contains(termPojo.getAlias())) {
                            termPojo.setValue(1);
                            if (!modulePojo.getEnable()) {
                                modulePojo.setEnable(true);
                            }
                        }
                        continue;
                    }

                    if (permissionIdsSet.contains(termPojo.getProPermissionId())) {
                        termPojo.setValue(1);
                        if (!modulePojo.getEnable()) {
                            modulePojo.setEnable(true);
                        }
                    }
                }
            }

            modulePojo.setPermission(modulePerms);
            if (saasNoDataPermissionIds.contains(module.getId())) {
                modulePojo.setDataPermission(-1);
            } else {
                if (saasDataPermissionMap.containsKey(id)) {
                    modulePojo.setDataPermission(saasDataPermissionMap.get(id));
                } else {
                    modulePojo.setDataPermission(role.getDataPermission());
                }
            }
            allModulePermissions.add(modulePojo);
        }
        allModulePermissions.addAll(allPaasPermissions);

    }

    /**
     * 通过动态权限，将菜单选中
     * @param modulePojo
     * @param dynamicPermissions
     */
    private void setEnableByDynamicPermissions(ModulePermissionWithNamePojo modulePojo, String dynamicPermissions) {
        List<DynamicPermissionPojo> dynamicPermissionPojos = JSON.parseArray(dynamicPermissions, DynamicPermissionPojo.class);
        Set<String> aliasSet = new HashSet<>();
        if (CollectionsUtil.isEmpty(dynamicPermissionPojos)) {
            return;
        }
        for (DynamicPermissionPojo dynamicPermissionPojo : dynamicPermissionPojos) {
            List<DynamicPermissionSubPojo> modules = dynamicPermissionPojo.getModules();
            for ( DynamicPermissionSubPojo dynamicPermissionSubPojo : modules ) {
                aliasSet.add(dynamicPermissionSubPojo.getAlias());
            }
        }
        if (aliasSet.contains(modulePojo.getAlias())) {
            modulePojo.setEnable(true);
        }
    }

    /**
     * 通过alias判断实现获取菜单名，修改name值
     * @param paasAliasToName
     * @param module
     * @param id
     * @param modulePojo
     */
    private void changeNameByAlias(Map<String, String> paasAliasToName, ProPermissionEntity module, long id, ModulePermissionWithNamePojo modulePojo) {
        String moduleName = module.getName();
        String menuName = paasAliasToName.get(module.getAlias());
        StringBuilder newName = new StringBuilder();
        modulePojo.setId(id);
        if (!Objects.equals(XbbRefTypeEnum.getByAlias(module.getAlias()).getName(),paasAliasToName.get(module.getAlias())) && StringUtil.isNotEmpty(paasAliasToName.get(module.getAlias()))) {
            newName.append(menuName).append("(").append(moduleName).append(")");
            modulePojo.setName(newName.toString());
        }else {
            modulePojo.setName(moduleName);
        }
    }

    private void removeSaasEsignPermission(Boolean esignEnable, ProPermissionEntity module) {
        List<ProPermissionEntity> childList = module.getChildList();
        if (esignEnable) {
            return;
        }
        String alias = module.getAlias();
        if (Objects.equals(alias, ProPermissionAliasEnum.CONTRACT.getAlias())) {
            for (ProPermissionEntity child : childList) {
                Integer id = child.getId();
                if (Objects.equals(id, 611)) {
                    childList.remove(child);
                    return;
                }
            }
        }


        if (Objects.equals(alias, ProPermissionAliasEnum.PURCHASE.getAlias())) {
            for (ProPermissionEntity child : childList) {
                Integer id = child.getId();
                if (Objects.equals(id, 612)) {
                    childList.remove(child);
                    return;
                }
            }
        }
        if (Objects.equals(alias, ProPermissionAliasEnum.QUOTATION.getAlias())) {
            for (ProPermissionEntity child : childList) {
                Integer id = child.getId();
                if (Objects.equals(id, 613)) {
                    childList.remove(child);
                    return;
                }
            }
        }
    }

    /**
     * 格式化paas应用模块权限，从数据库存储格式 ==> List<ModulePermissionWithNamePojo>
     * @param corpid 公司id
     * @param appId paas应用id
     * @param role 对应角色
     * @param allModulePermissions 格式化后的数据会存储在此队列
     */
    private void  formatPaasAppPermission(String corpid, Long appId, RoleEntity role, List<ModulePermissionWithNamePojo> allModulePermissions) {
        String dataPermissionDetailStr = role.getDataPermissionDetail();
        List<DataPermissionDetailPojo> dataPermissionDetailPojos = JSON.parseArray(dataPermissionDetailStr, DataPermissionDetailPojo.class);
        if (dataPermissionDetailPojos == null) {
            dataPermissionDetailPojos = new ArrayList<>();
        }
        Map<Long, Integer> idAndDataPermissionMap = new HashMap<>();
        for (DataPermissionDetailPojo pojo : dataPermissionDetailPojos) {
           if (Objects.equals(appId, pojo.getId())) {
               List<DataPermissionsPojo> permissions = pojo.getPermissions();
               for (DataPermissionsPojo dataPermissionsPojo : permissions) {
                   idAndDataPermissionMap.put(dataPermissionsPojo.getId(), dataPermissionsPojo.getDataPermission());
               }
           }
        }
        // 查找某应用下所有模块
        Map<String, Object> params = new HashMap<>(16);
        params.put("corpid", corpid);
        params.put("appId", appId);
        params.put("del", 0);
        params.put("typeIn", Arrays.asList(2, 3, 4));
        params.put("orderByStr", "sort");
        List<PaasMenuEntity> allModules = paasMenuModel.list(params);

        // 解析appPermissionPojo
        List<AppPermissionPojo> enableAppPermissions = JSON.parseArray(role.getPaasPermissions(), AppPermissionPojo.class);
        // 找到对应的appPermissionPojo
        AppPermissionPojo thisApp = null;
        if (enableAppPermissions == null) {
            enableAppPermissions = new ArrayList<>();
        }
        for (AppPermissionPojo enableApp : enableAppPermissions) {
            if (appId.equals(enableApp.getAppId())) {
                thisApp = enableApp;
                break;
            }
        }

        Map<Long, ModulePermissionPojo> enableModules = null;
        if (thisApp != null && thisApp.getModules() != null) {
            // 将module转化为有权限的module Map
            enableModules = new HashMap<>(16);
            for (ModulePermissionPojo enableModule : thisApp.getModules()) {
                if (enableModule != null) {
                    enableModules.put(enableModule.getId(), enableModule);
                }
            }
        }

        Boolean esignEnable = true;
        PaasAppEntity paasApp = paasAppModel.getByAlias(SystemAppMenuEnum.ESIGN.getAlias(), corpid);
        if (Objects.isNull(paasApp) || Objects.equals(paasApp.getEnable(), BasicConstant.ZERO)) {
            esignEnable = false;
        }

        // 模块数据权限,拼装数据
        List<PermissionComplexTermPojo> modulePerms = new ArrayList<>();
        for (PaasMenuEntity module : allModules) {
            Long id = module.getId();
            // 初始化默认paas模块权限
            if (!cloudCodeHelp.isCloudCodeAlias(module.getAlias())) {
                modulePerms = PermissionHelp.initDefaultPaasModulePermission();
            } else {
                modulePerms = new ArrayList<>();
            }
            removePaasEsignPermission(esignEnable, modulePerms);
            ModulePermissionWithNamePojo modulePojo = new ModulePermissionWithNamePojo();
            modulePojo.setId(id);
            modulePojo.setName(module.getName());
            modulePojo.setType(module.getType());
            modulePojo.setSaasMark(SaasMarkEnum.PAAS.getCode());
            modulePojo.setAlias(module.getAlias());
            // 默认设为 false, PermissionTermsPojo初始化,没有设置数据时传回初始值
            modulePojo.setEnable(false);
            Set<String> dynamicPermissionSet = cloudCodeHelp.getDynamicPermissionSet(role.getDynamicPermissions());
            if (dynamicPermissionSet.contains(module.getAlias())) {
                //有云叩权限
                modulePojo.setEnable(true);
            }

            cloudCodeHelp.addCloudCodePermission(module.getCorpid(), module.getAppId(), module.getId(), modulePerms);
            // 超级管理员和老板默认有所有paas权限
            if (role.isAdminOrBoss()) {
                modulePojo.setEnable(true);
                for (PermissionComplexTermPojo termPojo : modulePerms) {
                    termPojo.setValue(1);
                }
            } else if (enableModules != null && enableModules.containsKey(id)) {
                ModulePermissionPojo enableModule = enableModules.get(id);
                if (enableModule != null) {
                    modulePojo.setEnable(true);
                    PermissionTermsPojo enableModulePerms = enableModule.getPermission();
                    for (PermissionComplexTermPojo termPojo : modulePerms) {

                        if (cloudCodeHelp.isCloudCodeAlias(termPojo.getAlias())) {
                            if (dynamicPermissionSet.contains(termPojo.getAlias())) {
                                termPojo.setValue(1);
                            }
                            continue;
                        }

                        if (ReflectHelper.valueGet(enableModulePerms, termPojo.getAlias()).equals(1)) {
                            termPojo.setValue(1);
                        } else {
                            termPojo.setValue(0);
                        }
                    }
                }
            }
            modulePojo.setPermission(modulePerms);
            if (idAndDataPermissionMap.containsKey(id)) {
                modulePojo.setDataPermission(idAndDataPermissionMap.get(id));
            } else {
                modulePojo.setDataPermission(role.getDataPermission());
            }
            allModulePermissions.add(modulePojo);
        }
    }

    private void removePaasEsignPermission(Boolean esignEnable, List<PermissionComplexTermPojo> modulePerms) {
        if (esignEnable) {
            return ;
        }
        for (PermissionComplexTermPojo modulePerm : modulePerms) {
            String alias = modulePerm.getAlias();
            if (Objects.equals(alias, DefaultPaasModulePermissionEnum.ESIGN.getAlias())) {
                modulePerms.remove(modulePerm);
                return;
            }
        }


    }

    /**
     * saas应用权限保存逻辑
     * saas应用保存涉及三个集合
     * 集合A：角色已设置的所有权限集合
     * 集合B：该应用对应的所有权限集合
     * 集合C：前端本次保存该应用对应的权限集合
     * 最终保存值有两种思路：目前使用了思路1
     * 1）思路1 ： A - B + C 比较好理解
     * 2) 思路2 ： 循环B集合，有以下四种可能
     *             2.1 A在 C在，不用处理
     *             2.2 A在 C不在，A中需删除
     *             2.3 A不在 C在，A中需增加
     *             2.4 A不在 C不在，不用处理
     * @param appId saas应用id,saas应用该值对应的是该应用的proPermissionId
     * @param role 角色实体
     * @param modulePerms 前端传入的应用模块权限信息
     * @param corpid 公司id
     */
    private void saasPermissionSave(Long appId, RoleEntity role, List<ModulePermissionWithNamePojo> modulePerms, String corpid) {
        List<ModulePermissionWithNamePojo> saasModulePerms = new ArrayList<>();
        List<ModulePermissionWithNamePojo> paasModulePerms = new ArrayList<>();

        for (ModulePermissionWithNamePojo pojo : modulePerms) {

//            if (cloudCodeHelp.isCloudCodeAlias(pojo.getAlias())) {
//                continue;
//            }

            if (Objects.equals(pojo.getSaasMark(), SaasMarkEnum.SAAS.getCode())) {
                saasModulePerms.add(pojo);
            } else {
                paasModulePerms.add(pojo);
            }
        }

        // 表单级数据权限处理
        String dataPermissionDetailStr = role.getDataPermissionDetail();
        // 原来的数据权限
        List<DataPermissionDetailPojo> dataPermissionDetailPojos = JSON.parseArray(dataPermissionDetailStr, DataPermissionDetailPojo.class);
        if (dataPermissionDetailPojos == null) {
            dataPermissionDetailPojos = new ArrayList<>();
        }
        // 本次保存的数据权限
        List<DataPermissionsPojo> newDataPermissions = new ArrayList<>();

        // 已设置的saas权限列表 A集合
        Set<Integer> saasPermissionIdsSet = role.getPermissionIdsSet();
        // 该saas应用对应的权限列表 B集合
        Map<String, Object> params = new HashMap<>(16);
        params.put("routerStart", appId);
        params.put("del", 0);
        List<Integer> appPermissionIds = proPermissionModel.findEntityIds(params);

        // 格式化当前保存传过来的该应用权限列表，C集合
        Set<Integer> submitPermissionIds = new HashSet<>();
        // 应用也对应了saas中一条权限记录
        submitPermissionIds.add(appId.intValue());
        if (saasModulePerms != null) {
            for (ModulePermissionWithNamePojo permissionPojo : saasModulePerms) {
                if (permissionPojo.getEnable()) {
                    submitPermissionIds.add(permissionPojo.getId().intValue());
                    List<PermissionComplexTermPojo> complexTermPojos = permissionPojo.getPermission();
                    if (complexTermPojos == null) {
                        continue;
                    }
                    for (PermissionComplexTermPojo termPojo : complexTermPojos) {
                        if (termPojo.getValue().equals(1)) {
                            submitPermissionIds.add(termPojo.getProPermissionId());
                        }
                    }
                }

                // SaaS应用内的SaaS表单数据权限处理
                if (!Objects.equals(permissionPojo.getDataPermission(), -1)) {
                    DataPermissionsPojo dataPermissionsPojo = new DataPermissionsPojo();
                    dataPermissionsPojo.setId(permissionPojo.getId());
                    dataPermissionsPojo.setSaasMark(permissionPojo.getSaasMark());
                    dataPermissionsPojo.setDataPermission(permissionPojo.getDataPermission());
                    newDataPermissions.add(dataPermissionsPojo);
                }
            }
        }


        for (ModulePermissionWithNamePojo paasModulePerm : paasModulePerms) {
            // SaaS应用内的PaaS表单数据权限处理
            DataPermissionsPojo dataPermissionsPojo = new DataPermissionsPojo();
            dataPermissionsPojo.setId(paasModulePerm.getId());
            dataPermissionsPojo.setDataPermission(paasModulePerm.getDataPermission());
            dataPermissionsPojo.setSaasMark(SaasMarkEnum.PAAS.getCode());
            newDataPermissions.add(dataPermissionsPojo);
        }

        // 如果没有该应用内权限，则将该应用权限也去除
        if (submitPermissionIds.size() == 1) {
            if (paasModulePerms.size() > 0) {
                boolean isEnable = false;
                for (ModulePermissionWithNamePojo pojo : paasModulePerms) {
                    if (pojo.getEnable()) {
                        isEnable = true;
                    }
                }
                if (!isEnable) {
                    submitPermissionIds.remove(appId.intValue());

                }
            } else {
                submitPermissionIds.remove(appId.intValue());
            }
        }

        // A - B
        saasPermissionIdsSet.removeAll(appPermissionIds);
        // (A -B) + C
        saasPermissionIdsSet.addAll(submitPermissionIds);
        // 转化为字符串格式 |1|2|3|4|（用“|”分隔）
        String saasPermissionStr = StringUtil.arrayToString(saasPermissionIdsSet.toArray(), "|");
        role.setPermissions(saasPermissionStr);

        // SaaS应用内PaaS表单权限保存
        params.clear();
        params.put("aliasIn", ProPermissionAliasEnum.getAppPermissionAlias());
        List<ProPermissionEntity> proApppermissionList = proPermissionModel.findEntitys(params);
        ProPermissionAliasEnum proPermissionAliasEnum = null;
        for (ProPermissionEntity entity : proApppermissionList) {
            if (Objects.equals(entity.getId(), appId.intValue())) {
                proPermissionAliasEnum = ProPermissionAliasEnum.getByAlias(entity.getAlias());
                break;
            }
        }

        String appAlias = null;
        if (Objects.nonNull(proPermissionAliasEnum)) {
            switch (proPermissionAliasEnum) {
                case CRM:
                    appAlias = SystemAppMenuEnum.CRM.getAlias();
                    break;
                case JXC:
                    appAlias = SystemAppMenuEnum.JXC.getAlias();
                    break;
                case PRODUCT_MANAGEMENT:
                    appAlias = SystemAppMenuEnum.PRODUCT.getAlias();
                    break;
                case FUND_MANAGEMENT:
                    appAlias = SystemAppMenuEnum.FUND_MANAGEMENT.getAlias();
                    break;
                case WORK_ORDER_APP:
                    appAlias = SystemAppMenuEnum.WORK_ORDER.getAlias();
                    break;
                case MARKET_MANAGEMENT:
                    appAlias = SystemAppMenuEnum.MARKET_MANAGEMENT.getAlias();
                    break;
                case WORK_ORDER_V2_CENTER:
                    appAlias = SystemAppMenuEnum.WORK_ORDER_V2_CENTER.getAlias();
                    break;
                case CHART_CENTER:
                case PROCESS_APP:
                case MANAGE_CENTER:
                case SMS_APP:
                default:
            }
        }
        if (Objects.nonNull(appAlias)) {
            PaasAppEntity paasAppEntity = paasAppModel.getByAlias(appAlias, corpid);
            if (Objects.nonNull(paasAppEntity)) {
                Long paasAppId = paasAppEntity.getId();
                boolean findAppPerm = false;
                List<AppPermissionPojo> appPermissionPojos = JSON.parseArray(role.getPaasPermissions(), AppPermissionPojo.class);
                if (Objects.isNull(appPermissionPojos)) {
                    appPermissionPojos = new ArrayList<>();
                }
                Iterator<AppPermissionPojo> appPermIterator = appPermissionPojos.iterator();
                boolean atLeastOnePerm = false;
                while (appPermIterator.hasNext()) {
                    AppPermissionPojo appPerm = appPermIterator.next();
                    if (!paasAppId.equals(appPerm.getAppId())) {
                        continue;
                    }
                    if (paasModulePerms.size() > 0) {
                        // 修改该角色对应该应用的权限
                        atLeastOnePerm = setModulePerms(appPerm, paasModulePerms);
                        // 没有有效权限，删除该角色对应该应用的权限
                        if (!atLeastOnePerm) {
                            appPermIterator.remove();
                        }
                    } else {
                        //删除该角色对应该应用的权限
                        appPermIterator.remove();
                    }
                    findAppPerm = true;
                    break;
                }

                // 添加权限且原来没有该应用的权限
                if (!findAppPerm) {
                    AppPermissionPojo addAppPerm = new AppPermissionPojo();
                    addAppPerm.setAppId(paasAppId);
                    atLeastOnePerm = setModulePerms(addAppPerm, paasModulePerms);
                    if (atLeastOnePerm) {
                        appPermissionPojos.add(addAppPerm);
                    }
                }

                role.setPaasPermissions(JSON.toJSONString(appPermissionPojos));
            }
        }

        // 聚合原有的数据权限和新的数据权限
        boolean isNewDataPermission = true;
        for (DataPermissionDetailPojo pojo : dataPermissionDetailPojos) {
            if (Objects.equals(appId, pojo.getId())) {
                pojo.setPermissions(newDataPermissions);
                isNewDataPermission = false;
            }
        }
        if (isNewDataPermission && !newDataPermissions.isEmpty()) {
            DataPermissionDetailPojo dataPermissionDetailPojo = new DataPermissionDetailPojo();
            dataPermissionDetailPojo.setId(appId);
            dataPermissionDetailPojo.setSaasMark(SaasMarkEnum.SAAS.getCode());
            dataPermissionDetailPojo.setPermissions(newDataPermissions);
            dataPermissionDetailPojos.add(dataPermissionDetailPojo);
        }
        role.setDataPermissionDetail(JSON.toJSONString(dataPermissionDetailPojos));

    }

    /**
     * paas应用权限保存逻辑
     * @param appId paas应用id
     * @param role 角色实体
     * @param modulePerms 前端传入的应用模块权限信息
     */
    private void paasPermissionSave(Long appId, RoleEntity role, List<ModulePermissionWithNamePojo> modulePerms) {
        // 设置修改后的角色权限
        boolean findAppPerm = false;
        List<AppPermissionPojo> appPerms = JSON.parseArray(role.getPaasPermissions(), AppPermissionPojo.class);
        // 空权限处理
        if (appPerms == null) {
            appPerms = new ArrayList<>();
        }
        Iterator<AppPermissionPojo> appPermIterator = appPerms.iterator();
        // 判断应用是否至少包含一项有效权限
        boolean atLeastOnePerm = false;
        while (appPermIterator.hasNext()) {
            AppPermissionPojo appPerm = appPermIterator.next();
            if (!appId.equals(appPerm.getAppId())) {
                continue;
            }
            if (modulePerms != null && modulePerms.size() > 0) {
                // 修改该角色对应该应用的权限
                atLeastOnePerm = setModulePerms(appPerm, modulePerms);
                // 没有有效权限，删除该角色对应该应用的权限
                if (!atLeastOnePerm) {
                    appPermIterator.remove();
                }
            } else {
                //删除该角色对应该应用的权限
                appPermIterator.remove();
            }
            findAppPerm = true;
            break;
        }
        // 添加权限且原来没有该应用的权限
        if (!findAppPerm) {
            AppPermissionPojo addAppPerm = new AppPermissionPojo();
            addAppPerm.setAppId(appId);
            atLeastOnePerm = setModulePerms(addAppPerm, modulePerms);
            if (atLeastOnePerm) {
                appPerms.add(addAppPerm);
            }
        }

        role.setPaasPermissions(JSON.toJSONString(appPerms));


        // 表单级数据权限处理
        String dataPermissionDetailStr = role.getDataPermissionDetail();
        // 原来的数据权限
        List<DataPermissionDetailPojo> dataPermissionDetailPojos = JSON.parseArray(dataPermissionDetailStr, DataPermissionDetailPojo.class);
        if (dataPermissionDetailPojos == null) {
            dataPermissionDetailPojos = new ArrayList<>();
        }
        // 本次保存的数据权限
        List<DataPermissionsPojo> newDataPermissions = new ArrayList<>();
        for (ModulePermissionWithNamePojo pojo : modulePerms) {
            DataPermissionsPojo dataPermissionsPojo = new DataPermissionsPojo();
            dataPermissionsPojo.setId(pojo.getId());
            dataPermissionsPojo.setSaasMark(pojo.getSaasMark());
            dataPermissionsPojo.setDataPermission(pojo.getDataPermission());
            newDataPermissions.add(dataPermissionsPojo);
        }
        // 聚合原有的数据权限和新的数据权限
        boolean isNewDataPermission = true;
        for (DataPermissionDetailPojo pojo : dataPermissionDetailPojos) {
            if (Objects.equals(appId, pojo.getId())) {
                pojo.setPermissions(newDataPermissions);
                isNewDataPermission = false;
            }
        }
        if (isNewDataPermission) {
            DataPermissionDetailPojo dataPermissionDetailPojo = new DataPermissionDetailPojo();
            dataPermissionDetailPojo.setId(appId);
            dataPermissionDetailPojo.setSaasMark(SaasMarkEnum.PAAS.getCode());
            dataPermissionDetailPojo.setPermissions(newDataPermissions);
            dataPermissionDetailPojos.add(dataPermissionDetailPojo);
        }
        role.setDataPermissionDetail(JSON.toJSONString(dataPermissionDetailPojos));

    }

    private void dynamicPaasPermissionSave(Long appId, RoleEntity role, List<ModulePermissionWithNamePojo> modulePerms) {
        // 设置修改后的角色权限
        boolean findAppPerm = false;
        List<DynamicPermissionPojo> dynamicAppPerms = JSON.parseArray(role.getDynamicPermissions(), DynamicPermissionPojo.class);
        // 空权限处理
        if (dynamicAppPerms == null) {
            dynamicAppPerms = new ArrayList<>();
        }
        // 判断应用是否至少包含一项有效权限
        boolean atLeastOnePerm = false;


        Iterator<DynamicPermissionPojo> dynamicAppPermIterator = dynamicAppPerms.iterator();
        while (dynamicAppPermIterator.hasNext()) {

            DynamicPermissionPojo dynamicPerm = dynamicAppPermIterator.next();
            if (!appId.equals(dynamicPerm.getAppId())) {
                continue;
            }
            if (modulePerms != null && modulePerms.size() > 0) {
                // 修改该角色对应该应用的权限
                atLeastOnePerm = setDynamicModulePerms(dynamicPerm, modulePerms);
                // 没有有效权限，删除该角色对应该应用的权限
                if (!atLeastOnePerm) {
                    dynamicAppPermIterator.remove();
                }
            } else {
                //删除该角色对应该应用的权限
                dynamicAppPermIterator.remove();
            }
            findAppPerm = true;
            break;
        }



        // 添加权限且原来没有该应用的权限
        if (!findAppPerm) {
            DynamicPermissionPojo addAppPerm = new DynamicPermissionPojo();
            addAppPerm.setAppId(appId);
            atLeastOnePerm = setDynamicModulePerms(addAppPerm, modulePerms);
            if (atLeastOnePerm) {
                dynamicAppPerms.add(addAppPerm);
            }
        }

        role.setDynamicPermissions(JSON.toJSONString(dynamicAppPerms));


        // 表单级数据权限处理
        String dataPermissionDetailStr = role.getDataPermissionDetail();
        // 原来的数据权限
        List<DataPermissionDetailPojo> dataPermissionDetailPojos = JSON.parseArray(dataPermissionDetailStr, DataPermissionDetailPojo.class);
        if (dataPermissionDetailPojos == null) {
            dataPermissionDetailPojos = new ArrayList<>();
        }
        // 本次保存的数据权限
        List<DataPermissionsPojo> newDataPermissions = new ArrayList<>();
        for (ModulePermissionWithNamePojo pojo : modulePerms) {
            DataPermissionsPojo dataPermissionsPojo = new DataPermissionsPojo();
            dataPermissionsPojo.setId(pojo.getId());
            dataPermissionsPojo.setSaasMark(pojo.getSaasMark());
            dataPermissionsPojo.setDataPermission(pojo.getDataPermission());
            newDataPermissions.add(dataPermissionsPojo);
        }
        // 聚合原有的数据权限和新的数据权限
        boolean isNewDataPermission = true;
        for (DataPermissionDetailPojo pojo : dataPermissionDetailPojos) {
            if (Objects.equals(appId, pojo.getId())) {
                pojo.setPermissions(newDataPermissions);
                isNewDataPermission = false;
            }
        }
        if (isNewDataPermission) {
            DataPermissionDetailPojo dataPermissionDetailPojo = new DataPermissionDetailPojo();
            dataPermissionDetailPojo.setId(appId);
            dataPermissionDetailPojo.setSaasMark(SaasMarkEnum.PAAS.getCode());
            dataPermissionDetailPojo.setPermissions(newDataPermissions);
            dataPermissionDetailPojos.add(dataPermissionDetailPojo);
        }
        role.setDataPermissionDetail(JSON.toJSONString(dataPermissionDetailPojos));
    }

    private boolean setDynamicModulePerms(DynamicPermissionPojo dynamicAppPerm, List<ModulePermissionWithNamePojo> modulePerms) {

        if (modulePerms == null || modulePerms.size() <= 0) {
            return false;
        }
        List<DynamicPermissionSubPojo> dynamicPermissionSubs = new ArrayList<>();
        // 为解决应用内所有表单权限置空后，应用权限也置空逻辑
        boolean atLeastOnePerm = false;
        for (ModulePermissionWithNamePojo modulePerm : modulePerms) {
            if (Boolean.TRUE.equals(modulePerm.getEnable())) {

                if (cloudCodeHelp.isCloudCodeAlias(modulePerm.getAlias())) {
                    //云叩菜单
                    DynamicPermissionSubPojo dynamicPermissionSubPojo = new DynamicPermissionSubPojo();
//                    dynamicPermissionSubPojo.setFormId();
                    dynamicPermissionSubPojo.setAlias(modulePerm.getAlias());
                    dynamicPermissionSubPojo.setName(modulePerm.getName());
                    dynamicPermissionSubs.add(dynamicPermissionSubPojo);
                    atLeastOnePerm = true;
                    continue;
                }
                ModulePermissionPojo module = new ModulePermissionPojo();
                BeanUtil.copyProperties(modulePerm, module);
                // 转换 List<PermissionComplexTermPojo> ==> PermissionTermsPojo
                List<PermissionComplexTermPojo> complexTermPojos = modulePerm.getPermission();
                if (complexTermPojos != null && complexTermPojos.size() > 0) {
                    for (PermissionComplexTermPojo complexTermPojo : complexTermPojos) {
                        if (cloudCodeHelp.isCloudCodeAlias(complexTermPojo.getAlias()) && Objects.equals(complexTermPojo.getValue(), BasicConstant.ONE)) {
                            //云叩权限
                            DynamicPermissionSubPojo dynamicPermissionSubPojo = new DynamicPermissionSubPojo();
//                            dynamicPermissionSubPojo.setFormId();
                            dynamicPermissionSubPojo.setAlias(complexTermPojo.getAlias());
                            dynamicPermissionSubPojo.setName(complexTermPojo.getName());
                            dynamicPermissionSubs.add(dynamicPermissionSubPojo);
                            atLeastOnePerm = true;
                            continue;
                        }
                    }
                }
            }
        }
        if (atLeastOnePerm) {
            dynamicAppPerm.setModules(dynamicPermissionSubs);
        }
        return atLeastOnePerm;

    }

    /**
     * 计算角色列表中每个系统角色是否被本公司修改过
     * @param roleVOs 角色列表
     * @param corpid 公司id
     */
    private void setSysRoleModifyFlag(List<RoleVO> roleVOs, String corpid) {
        Map<String, Object> param = new HashMap<>(16);
        param.put("del", 0);
        param.put("corpid", corpid);
        List<CoverRoleEntity> coverRoleEntities = coverRoleModel.findEntitys(param);
        // 这里量级比较小，就不额外增加map结构，直接两次循环
        for (CoverRoleEntity coverRole : coverRoleEntities) {
            for (RoleVO roleVO : roleVOs) {
                if (roleVO.getCorpid().equals(PaasConstant.DEFAULT_DATA_CORPID)
                        && coverRole.getRoleId().equals(roleVO.getId())) {
                    roleVO.setModified(true);
                    break;
                }
            }
        }
    }

    /**
     * 判断有无开启AI套餐
     */
    private IsActiveAIComboVO isActiveAICombo(String corpid)throws XbbException{
        //判断是否开启套餐
        IsActiveAIComboVO vo = new IsActiveAIComboVO();
        vo.setIsExpired(false);
        XbbResponse<IsActiveAIComboVO> response = new XbbResponse<>(vo);
        try {
            BaseDTO baseDTO = new BaseDTO();
            baseDTO.setCorpid(corpid);
            baseDTO.setUserId("0");
            baseDTO.setPlatform("web");
            String lang = LocaleContextHolder.getLocale().toString();
            response = aiFeignClient.isActiveCombo(baseDTO, lang);
            if (!Objects.equals(response.getCode(), ErrorCodeEnum.API_SUCCESS.getCode())) {
                return vo;
            }
        }catch (Exception e){
            LOG.info("corpid为{}未开启AI",corpid);
        }
        return response.getResult();
    }

    /**
     * 系统角色排序
     *
     * @param roleVOs 角色信息
     * @return 排序后的系统角色
     */
    public List<RoleVO> sortSysRole(List<RoleVO> roleVOs) {
        try {
            // 防止万一出异常，客户角色界面出问题
            List<RoleVO> oldList = new ArrayList<>();
            for (RoleVO roleVO : roleVOs) {
                oldList.add(roleVO);
            }
            List<RoleEnum> roleEnumList = new ArrayList<>(Arrays.asList(RoleEnum.values()));
            roleEnumList.sort((o1, o2) -> {
                int i = o1.getSort() - o2.getSort();
                if (i == 0) {
                    return o1.getSort() - o2.getSort();
                }
                return i;
            });
            List<Integer> codeList = roleEnumList.stream().map(RoleEnum::getCode).collect(Collectors.toList());
            Map<Integer, RoleVO> roleMap = roleVOs.stream().filter(role -> codeList.contains(role.getId())).collect(Collectors.toMap(RoleVO::getId, role -> role));
            List<RoleVO> sortList = new ArrayList<>(roleEnumList.size());
            for (RoleEnum roleEnum : roleEnumList) {
                if (!roleMap.containsKey(roleEnum.getCode())) {
                    continue;
                }
                sortList.add(roleMap.get(roleEnum.getCode()));
            }
            oldList.removeAll(roleMap.values());
            sortList.addAll(oldList);
            return sortList;
        } catch (Exception e) {
            return roleVOs;
        }
    }
}
